File Input Output Operations In C++

A Study On File Input Output Operations & File Pointer Functions In C++.

In real-time programming, we deal with large chunks of data that cannot be accommodated from standard Input-Output devices. Hence we need to make use of secondary storage for storing data. Using secondary storage we usually store data in the form of files.

We can read data from files or write data into files by using a sequence of data called streams either in the text or binary format. There are various input /output and other operation related to files in C++. This tutorial explains these operations related to files using various classes.

=> Visit Here For The Exclusive C++ Training Tutorial Series.

File Input Output in C++

File Input/Output Classes In C++

We have seen an iostream class in C++ which defines the standard input and output functionality including cin and cout. This class is limited to the standard input and output devices like keyboard and monitor respectively.

When it comes to file operations, C++ has a different set of classes that can be used.

These classes are described as below:

  • Ofstream: File handling class that signifies the output file stream and is used for writing data to files.
  • Ifstream: File handling class that signifies the input file stream and is used for reading data from the file.
  • Fstream: File handling class that has the ability to handle both ifstream and ofstream. It can be used to read from and write to a file.

The following operations are supported, in C++ File Handling:

  • Open a file
  • Close a file
  • Read from a file
  • Write to a file

Let us see each of these operations in detail!!

Open A File

Associating object of one of the stream classes to a file either for reading or writing or both is called opening a file. An open file is represented in code by using this stream object. Thus any reading/writing operation performed on this stream object will be applied to the physical file as well.

The general syntax to open a file with the stream is:

void open(const char* filename, ios::open mode mode)


filename => The string containing path and name of the file to be opened.

mode => Optional parameter indicating the mode in which the file is to be opened.

C++ supports various modes in which the file can be opened. We can also specify a combination of these modes using the OR operator.

File modeDescription
ios::inOpens the file in input mode for reading.
ios::outOpens the file in output mode for writing data to file.
ios::ateSet initial position at the end of the file. If the end of file flag is not set, the initial position is set to the beginning of the file.
ios::truncIf the file is opened for writing and already has contents, the contents are truncated.
ios::appOpens the file in append mode such that all contents are appended at the end of the file.
ios::binaryOpens file in binary mode.

For Example, if we want to open a file “myfile.dat” for appending data in binary mode, then we can write the following code.

 ofstream myfile;“myfile.dat”, ios::out|ios::app|ios::binary);

As already mentioned, the mode parameter is optional. When we open a file without specifying the second parameter, an open member function of ofstream, ifstream or fstream has a default mode to open the file with.

These are given as follows:

ClassDefault mode

So, if we do not specify the second parameter in the open function, depending on the stream class used, the file is opened with the default mode.

Closing A File

We can use the close function to close a file and release the resources held by the file when we are done with the input and output operations on a file.

Function to close a file is:

void close()

So, when we are done with the operations on the above file myfile, we can close the file as follows:


Once the file is closed using the close function, the file object associated can be re-used to open another file.

Reading From A File

We can read the information from a file line by line using the stream extraction operator (>>). This is similar to reading input from the standard input using cin. The only difference being in case of files, we use ifstream or fstream object instead of cin.

Sample code for reading from a file is given below:

ifstream myfile;“samp_file.txt”);
cout<<”Reading from a file”<<endl; myfile>>data;

In the above code, we open a file and using the stream extraction operator (>>), we read the contents of the file. Once done with reading, we can close the file.

Writing To A File

We can also write data to a file using the file operations. The operator we use to write data to a file is a stream insertion operator (<<). Once again this is the same operator that we use to print data to a standard output device using cout. Difference between the two is that for file related writing we use ofstream or fstream object.

Let us consider the following Example code:

char data[100];
ofstream myfile;“samp_file.txt”);
cout<<”Enter the string to be written to file”<<endl;
cin.getline(data, 100);

Here, we read a line from the input and write it to a file that was opened with the ofstream object.

In the code example below, we provide a demonstration of all the file handling operations.

#include <fstream>
#include <iostream>
using namespace std;
int main () 
    char data[100];
    // opening a file in write mode.
    ofstream myfile;"E:\\message.txt");
    cout << "Writing to the file" << endl;
    cout << "Enter your name: ";
    cin.getline(data, 100);
    myfile << data << endl;
    cout << "Enter your age: "; cin >> data;
    myfile << data << endl;
    // close the opened file.
   // opening a file in read mode.
   ifstream infile;"E:\\message.txt");
   cout << "Reading from a file" << endl; infile >> data;
   cout << data << endl; infile >> data;
   cout << data << endl;
   return 0;


Writing to the file
Enter your name: Ved
Enter your age: 7
Reading from a file

In the above program first, we open a file in the write mode. Then we read data i.e. name and age and write it to a file. We then close this file. Next, we open the same file in the read mode and read the data line by line from the file and output it to the screen.

Thus this program covers all the file I/O operations.

File State Slags

There are some member functions that are used to check the state of the file. All these functions return a Boolean value.

We have tabularized these functions as follows:

eof()Returns true if the end of file is reached while reading the file.
fail()Returns true when read/write operation fails or format error occurs
bad()Returns true if reading from or writing to a file fail.
good()Returns  false  in the same cases in which calling any of the above functions would return  true.

Get/Put And Other Special Operations

The file I/O streams that we have seen so far have an internal get and put positions similar to the other I/O streams like iostream.

The class ifstream has an internal get position that contains the location of the element/character to be read in the file in the next input operation. The class ofstream has an internal put position that contains the location of the element/character to be written in the next output operation.

Incidentally, fstream has both get and put positions.

To facilitate reading and writing using these positions, we have a few member functions that are used to observe and modify these positions.

These functions are listed below:

tellg()Returns current position of get pointer
tellp()Returns current position of put pointer
seekg(position)Moves get a pointer to specified location counting from the beginning of the file
seekg(offset,direction)Moves get a pointer to offset value relative to the point given by parameter direction.
seekp(position)Moves put a pointer to specified location counting from the beginning of the file
seekp(offset, direction)Moves put a pointer to offset value relative to the point given by parameter direction.

The parameter direction given in the above function prototypes is an enumerated type of type seekdir and it determines the point from which the offset is counted.

It can have the following values.

ios::begOffset from beginning of the stream
ios::curOffset from current position
ios::endOffset from the end of the stream

Let us see a complete Example that demonstrates the usage of these functions.

#include <iostream>
#include <fstream>
using namespace std;
int main()
    fstream myfile;"E:\\myfile.txt",ios::out);
         cout<<"Cannot create File...";
        cout<<"New file created"<<endl;
        myfile<<"This is file input output tutorial";
cout<<"Initial File Pointer Position at: "<<myfile.tellp()<<endl;
       myfile.seekp(-1, ios::cur);
cout<<"After seekp(-1, ios::cur), File Pointer Position at: "<<myfile.tellp()<<endl;
       cout<<"Cannot open File...No such file";
     char ch;
     myfile.seekg(5, ios::beg);
cout<<"After seekg(5, ios::beg), File Pointer at: "<<myfile.tellg()<<endl;
        myfile.seekg(1, ios::cur);
cout<<"After seekg(1, ios::cur), File Pointer at: "<<myfile.tellg()<<endl;
return 0;


New file created

Initial File Pointer Position at: 34

After seekp(-1, ios::cur),File Pointer Position at: 33

After seekg(5, ios::beg), File Pointer at: 5

After seekg(1, ios::cur), File Pointer at: 6

file IO - New file created

As shown in the above program, we have a file created in which we write a line of text. Then using the various functions described above, we display various positions of the File Pointer.


In this tutorial, we have seen the various file operations to open, close and read/write data from/to a file.

We have also seen the functions to change the file pointer in order to access specific positions in the file. In our subsequent tutorials, we will discuss a few more important topics related to C++.

=> Read Through The Easy C++ Training Series.