Planet For Application Life Development Presents
MY IT World

Explore and uptodate your technology skills...

CPP Files and Streams

Files are a means to store data in a storage device. C++ file handling provides a mechanism to store output of a program in a file and read from a file on the disk. So far, we have been using header file which provide functions cin and cout to take input from console and write output to a console respectively. Now, we introduce one more header file which provides data types or classes ( ifstream , ofstream , fstream ) to read from a file and write to a file.

File Opening Modes

A file can be opened in different modes to perform read and write operations. Function to open a file i.e open( ) takes two arguments : char *filename and ios :: mode. C++ supports the following file open modes :

ModeExplanation
ios :: inOpen a file for reading
ios :: outOpen a file for writing
ios :: appAppends data to the end of the file
ios :: ateFile pointer moves to the end of the file but allows to writes data
in any location in the file
ios :: binaryBinary File
ios :: truncDeletes the contents of the file before opening

If a file is opened in ios :: out mode, then by default it is opened in ios :: trunc mode also i.e the contents of the opened file is overwritten. If we open a file using ifstream class, then by default it is opened in ios :: in mode and if we open a file using ofstream class, then by default it is opened in ios :: out mode. The fstream class doesn't provide any default mode.

File Operations using ifstream and ofstream

Open a file for writing :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<fstream>
using namespace std;
int main() {
   ofstream ofile; // declaring an object of class ofstream
   ofile.open("file.txt"); // open "file.txt" for writing data
   /* write to a file */
   ofile << "This is a line in a file" << endl;
   ofile << "This is another line" << endl;
   /* write to a console */
   cout << "Data written to file" << endl;
   ofile.close(); // close the file
   return 0;
}

Open a file for reading :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<fstream>
using namespace std;
int main() {
   char data[100]; // buffer to store a line read from file
   ifstream ifile; // declaring an object of class ifstream
   ifile.open("file.txt"); // open "file.txt" for reading
   cout << "Reading data from a file :-" << endl << endl;
   while (!ifile.eof()) { // while the end of file [ eof() ] is not reached 
      ifile.getline(data, 100); // read a line from file
      cout << data << endl; // print the file to console
   }
   ifile.close(); // close the file
   return 0;
}

In the first program, a file " file.txt " is created and some data is written into it. The file is created in the same directory in which the program file is saved. In the second program, we read the file line by line using and then print each line on the console. The while loop continues till the end of file is reached. We ensure that using the condition while( ! ifile.eof( ) ). Note that we can simply use while( ifile ) also. We can open a file using the constructors of ifstream and ofstream classes instead of using open( ) member function. For e.g, ifstream ifile( "file.text" );. It is a good practice to check if file is opened successfully before proceeding with further operations.

Manipulation of file pointers

The read operation from a file involves get pointer. It points to a specific location in the file and reading starts from that location. Then, the get pointer keeps moving forward which lets us read the entire file. Similarly, we can start writing to a location where put pointer is currently pointing. The get and put are known as file position pointers and these pointers can be manipulated or repositioned to allow random access of the file. The functions which manipulate file pointers are as follows :

FunctionDescription
seekg( )Moves the get pointer to a specific location in the file
seekp( )Moves the put pointer to a specific location in the file
tellg( )Returns the position of get pointer
tellp( )Returns the position of put pointer

The function seekg( n, ref_pos ) takes two arguments : n denotes the number of bytes to move and ref_pos denotes the reference position relative to which the pointer moves. ref_pos can take one of the three constants : ios :: beg moves the get pointer n bytes from the beginning of the file, ios :: end moves the get pointer n bytes from the end of the file and ios :: cur moves the get pointer n bytes from the current position. If we don't specify the second argument, then ios :: beg is the default reference position.