File Handling in C
File Handling in C
File Handling in C
The files handled so far have all been temporary files (data files); the data created by these files
could not be stored for later use. The data could not be used by other programs created later.
These files use the iostream standard library, which provides cin and cout methods for reading
from standard input and writing to standard output respectively.
C++ however provides a way or a mechanism for creating files which can s tore data
permanently, data which can be saved on disk and then used later. These files allow data to be
stored permanently and also allow transfer of input - data or output - data from one computer
to another to be easily done by using files.
To read and write to or from such files requires another standard C++ library called fstream,
which defines three new data types:
1 ofstream
This data type represents the output file stream and is used to create files and to
write information to files. This class signifies the output file stream and is applied
to create files for writing information to files.
2 ifstream
This data type represents the input file stream and is used to read information
from files. It signifies the input file stream and is applied for reading information
from files.
3 fstream
This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files,
and read information from files. This Stream class can be used for both read and
Page 1 of 11
FILE HANDLING IN C++
write from/to files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
Naming a file
Opening a file
Reading data from file
Writing data into file
Closing a file
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.
Page 2 of 11
FILE HANDLING IN C++
Before performing any operation on a file, you must first open it. If you need to write to the file,
open it using fstream or ofstream objects. If you only need to read from the file, open it using the
ifstream object.
The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in
them. The function takes this syntax:
Here, fileName specifies the name and location of the file to be opened and mode defines the
mode in which the file should be opened. The mode parameter is optional. It can take any of the
following values:
1 ios::app
Append mode. All output to that file to be appended to the end. All output
operations are performed at the end of the file, appending the content to the
current content of the file.
2 ios::ate
Open a file for output and move the read/write control to the end of the file. Set
the initial position at the end of the file. If this flag is not set, the initial position is
the beginning of the file.
3 ios::in
4 ios::out
Page 3 of 11
FILE HANDLING IN C++
Open a file for writing.
5 ios::trunc
If the file is opened for output operations and it already existed, its previous
content is deleted and replaced by the new one. If the file already exists, its
contents will be truncated before opening the file.
6 ios::binary
You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists, following
will be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
In an similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
or
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Each of the open member functions of classes ofstream, ifstream and fstream has a default mode
that is used if the file is opened without a second argument:
Page 4 of 11
FILE HANDLING IN C++
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively
assumed, even if a mode that does not include them is passed as second argument to
the open member function (the flags are combined).
For fstream, the default value is only applied if the function is called without specifying any
value for the mode parameter. If the function is called with any value in that parameter the
default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any
format considerations. Non-binary files are known as text files, and some translations may occur
due to formatting of some special characters (like newline and carriage return characters).
Closing a File
When we are finished with our input and output operations on a file we shall close it so that the
operating system is notified and its resources become available again. For that, we call the
stream's member function close. This member function takes flushes the associated buffers and
closes the file:
myfile.close();
Once this member function is called, the stream object can be re-used to open another file, and
the file is available again to be opened by other processes.
In case that an object is destroyed while still associated with an open file, the destructor
automatically calls the member function close.
Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
Page 5 of 11
FILE HANDLING IN C++
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open("example.txt");
myfile << "Writing this to a file.\n";
myfile.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.
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.
Page 6 of 11
FILE HANDLING IN C++
Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they
store it in the binary form (0's and 1's).
They can hold a larger amounts of data, are not readable easily, and provides better security than
text files.
Writing operations on text files are performed in the same way we operated with cout:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Reading from a file can also be performed in the same way that we did with cin:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
Page 7 of 11
FILE HANDLING IN C++
myfile.close();
}
return 0;
}
This last example reads a text file and prints out its content on the screen. We have created a
while loop that reads the file line by line, using getline. The value returned by getline is a
reference to the stream object itself, which when evaluated as a Boolean expression (as in this
while-loop) is true if the stream is ready for more operations, and false if either the end of the file
has been reached or if some other error occurred.
#include <iostream>
#include <fstream>
int main()
double mark;
ofstream outFile;
outFile.open("myFile.txt");
if(outFile.is_open())
cin>>studNum;
outFile<<studNum<<endl;
Page 8 of 11
FILE HANDLING IN C++
cout<<"Enter student name ";
cin>>studName;
outFile<<studName<<endl;
cin>>mark;
outFile<<mark<<endl;
else
outFile.close();
return 0;
Appending a file
#include <iostream>
#include <fstream>
int main()
if(appFile.is_open())
appFile<<line ;
Page 9 of 11
FILE HANDLING IN C++
cout<<" File appended successfully \n";
else
appFile.close();
return 0;
bad()
Returns true if a reading or writing operation fails. For example, in the case that we try to
write to a file that is not open for writing or if the device where we try to write has no
space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens,
like when an alphabetical character is extracted when we are trying to read an integer
number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of
the previous functions would return true. Note that good and bad are not exact opposites
(good checks more state flags at once).
The member function clear() can be used to reset the state flags.
Page 10 of 11
FILE HANDLING IN C++
Functions use in File Handling
Function Operation
Page 11 of 11