Files in C++: Opening A File
Files in C++: Opening A File
When a program runs, the data is in the memory but when it ends or the computer shuts
down, it gets lost. To keep data permanently, we need to write it in a file.
File is used to store data. In this topic, you will learn about reading data from a file and
writing data to the file.
fstream is another C++ standard library like iostream and is used to read and write on
files.
These are the data types used for file handling from the fstream library:
These are the data types used for file handling from the fstream library:
Data
Description
type
It can perform the function of both ofstream and ifstream which means it
fstream
can create files, write on files, and read from files.
Opening a file
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And
ifstream object is used to open a file for reading purpose only.
A file can be opened in two ways:
i)using constructor function of the class.
ii) Using member function open() of the class.
The first method is preferred when a single file is used with a stream. However, for managing
multiple files with the same stream, the second method is preferred.
The constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize
file stream objects with the filenames passed to them. This is carried out as explained
here:
To open a file named myfile as an input file we shall create a file stream object of input
type i.e., ifstream type. Here is an example:
The above given statement creates an object, fout, of output file stream.
There may be situations requiring a program to open more than one file. The strategy
for opening multiple files depends upon how they will be used. To use this approach,
declare a stream object without initializing it, then use a second statement to associate
the stream with a file. For example,
Following table lists the filemodes available in C++ with their meaning :
Stream
Constant Meaning
Type
Closing a file
C++ automatically close and release all the allocated memory. But a programmer
should always close all the opened files. The syntax for closing a file is:
stream_object.close();
for example
fin.close() ;
fout.close() ;
#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream file;
file.open ("example.txt");
file.close();
return 0;
}
Text files
Text file streams are those where the ios::binary flag is not included in their opening mode.
These files are designed to store text and thus all values that are input or output from/to them can
suffer some formatting transformations, which do not necessarily correspond to their literal binary
value.
fout.open("scores.dat", ios::out);
fout<<grade<<endl;
fout<<"Mr. Spock\n";
fin.open("myfile.dat", ios::in);
//to read one number and //to read one number and
//one string variable //one string variable
int number; int number;
apstring item; apstring item, dummy;
fin>>number>>item; getline(fin, item);
fin>>item;
This format is OK only if the getline(fin,dummy);
string variable is
a singleword. This format is needed if the
string variable contains
whitespace.
When data is stored in a file in the binary format, reading and writing data is faster because no
time is lost in converting the data from one format to another format. Such files are called
binary files. These file streams are those where the ios::binary flag is included in their opening
mode. For binary files, reading and writing data with the extraction and insertion operators
(<< and >>) and functions like getline is not efficient. File streams include two member
functions specifically designed to read and write binary data sequentially: write and read. The
first one (write) is a member function of ostream (inherited by ofstream). And read is a member
function of istream (inherited by ifstream). Objects of class fstream have both. Their prototypes
are:
Where memory_block is of type char* (pointer to char), and represents the address of an array
of bytes where the read data elements are stored or from where the data elements to be
written are taken. The size parameter is an integer value that specifies the number of
characters to be read or written from/to the memory block.
Program to write and read an object in, from binary file using write()
and read()
#include<iostream>
#include<fstream>
#include<cstdio>
class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}
void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}
};
int main()
{
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);
Student obj;
obj.setData();
outFile.close();
while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
inFile.close();
return 0;
}
File Pointers
The C++ input and output system manages two integer values associates with a file.
These are:
• get pointer – specifies the location in a file where the next read operation will occur.
• put pointer – specifies the location in a file where the next write operation will occur.
In other words, these pointers indicate the current positions for read and write operations,
respectively. Each time an input or an output operation takes place, the pointers are automatically
advances sequentially. The seekg() and tellg() functions allow you to set and examine the
get_pointer, and the seekp() and tellp() functions perform these operations on the put_pointer.
The The seekg() or seekp(), when used according to Form 1, then it moves the get_pointer or
put_pointer to an absolute position.for example
ifstream fin;
ofstream fout;
fin.seekg(30);// will move the get_pointer to byte number 30 in the file
fout.seekp(30);// will move the put_pointer to byte number 30 in the file
When seekg() or seekp() function is used according to Form 2, then it moves the
get_pointer or put_pointer to a position relative to the current position, following the
definition of seek_dir. Since, seek_dir is an enumeration defined in the header file
iostream.h, that has the following values:
Here is an example.