File Handling in CPP
File Handling in CPP
Files are used to store data in a storage device permanently. File handling provides a mechanism to
store the output of a program in a file and to perform various operations on it.
A stream is an abstraction that represents a device on which operations of input and output are
performed. A stream can be represented as a source or destination of characters of indefinite length
depending on its usage.
In C++, we have a set of file handling methods. These include ifstream, ofstream, and fstream. These
classes are derived from fstrembase and from the corresponding iostream class. These classes, designed
to manage the disk files, are declared in fstream, therefore we must include fstream, and therefore we
must include this file in any program that uses files.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
ofstream: This Stream class signifies the output file stream and is applied to create files for
writing information to files.
ifstream: This Stream class signifies the input file stream and is applied for reading information
from files.
fstream: This Stream class can be used for both read and write from/to files.
All the above three classes are derived from fstreambase and from the corresponding iostream class and
they are designed specifically to manage disk files.
Opening a File
Generally, the first operation performed on an object of one of these classes is to associate it to a real
file. This procedure is known to open a file.
We can open a file using any one of the following methods:
1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open () function.
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a class so we need to
create an object of this class to use its member functions. So we create new_file object and call open()
function. Here we use out mode that allows us to open the file to write in it.
Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to file
new_file.close();
}
return 0;
}
Explanation
Here we first create a new file “new_file_write” using open() function since we wanted to send output
to the file so, we use ios::out. As given in the program, information typed inside the quotes after
Insertion Pointer “<<” got passed to the output file.
Reading from a File
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
{
cout<<"No such file";
}
else
{
char ch;
while (!new_file.eof())
{
new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}}
Explanation
In this example, we read the file that generated id previous example i.e. new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above example, we print the content of
the file using extraction operator >>.
Close a File
It is simply done with the help of close() function.
Syntax: File Pointer.close()
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Output:
The file gets closed.
Detecting EOF
When a file is created and saved, a special invisible character called the eof character (which
stands for the end of file character), is automatically placed at the end of the file.
Every input file stream has a member function called eof, that can be used to detect this eof
character to determine if there is any more data to be read from the file that is connected to the
input file stream.
This member function is used as follows:
Input_Stream.eof( );
The eof function takes no argument and returns a Boolean value that can be used to control loops and
if-statements.
The Boolean value returned by the eof function is true only if the program has attempted to
read past the end of the input file, otherwise the value returned is false.
If fin is an input file stream that has been connected to an external file, then the entire content
of the file is read and then written to the screen with the following while-loop:
char next;
fin.get(next);
while ( !fin.eof( ) )
{
cout << next;
fin.get(next);
}
The ordering of the above programming codes is absolutely crucial because fin.eof( ) does not
become true until an attempt to read past the end of the file is made. Changing the order of the
codes will likely result in an undesire output for the final looping sequence. For example,
someone may write the above codes as follow:
char next;
while ( !fin.eof( ) )
{
fin.get(next);
cout << next;
}
If you read these lines superficially, it appears that the correct things are being done: while the end-of-
file has not been reached, read the next character from the file and print it out onto the screen. It turns
out the above loop almost works except that the last character is always printed twice. To see that,
consider what happens inside the loop while there is still one last character to be read. The character is
read without the member function eof( ) of fin to become false. The character is then displayed on the
screen. The loop is entered one more time, but this time the attempt to read a character from fin fails
and eof( ) becomes true. Notice as a result, the value stored in the variable "next" remains unchanged.
However we are still inside the loop. The following output statement to the screen forces the last
character to be displayed a second time. The loop is then finally exited.
Although using the eof function to detect the end of a file can work with the file containing
numerical as well as text data, some people uses the eof function for test data and uses the
extraction operator >> for numerical data.
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void add_plus_plus(ifstream& in_stream, ofstream& out_stream);
//Precondition: in_stream has been connected to an input file with open.
//out_stream has been connected to an output file with open.
//Postcondition: The contents of the file connected to in_stream have been
//copied into the file connected to out_stream, but with each 'C' replaced
//by "C++". (The files are not closed by this function.)
int main( )
{
ifstream fin;
ofstream fout;
fin.open("cad.dat");
if (fin.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("cplusad.dat");
if (fout.fail())
{
cout << "Output file opening failed.\n";
fin.close( );
exit(1);
}
add_plus_plus(fin, fout);
fin.close( );
fout.close( );
cout << "End of editing files.\n";
return 0;
}
void add_plus_plus(ifstream& in_stream, ofstream& out_stream)
{
char next;
in_stream.get(next);
while (! in_stream.eof())
{
if (next == 'C')
out_stream << "C++";
else
out_stream << next;
in_stream.get(next);
}
}