File Handling in C++

File In a computer system files are used to store the necessary information / data stored. There are mainly two types of files:

  1. Text file
  2. Binary file

Text file. It stores information/data in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character.

Binary file. It contains the data/information in the same format as it is held in memory. In binary files, no delimiters or EOF are used for a line for terminate the line

Classes for file stream operation

By using stream classes we can perform different operation such as read a file or write a file. There are some stream classes:

  • ofstream: This stream class is used to write on files
  • ifstream: This stream class is used to read from files
  • fstream:  This stream class is used to both read and write from/to files.

Modes  of  file

Mode

Description

ios::in

open file for reading only

ios::out

open file for writing only

ios::binary

Open file in a binary mode.

ios::ate

Set the initial position at the end of the file.
If the value of flag is not set to any value, then the by default initial position is the beginning of the file.

ios::app

All output operations are performed at the end of the file.

ios::trunc

If the file opened for output operations,then its previous content is deleted and replaced by the new one.

Opening a file:There are two ways for open a file:-

OPENING FILE USING CONSTRUCTOR

ofstream fout(“file1”);    //open a file “file1” for output only
ifstream fin(“data”);  //open a file “data” for input only

OPENING FILE USING open()

Stream-object.open(“filename”, mode)
      ofstream ofile;
      ofile.open(“data1”);  	// open a file “data1” for write only
      
      ifstream ifile;
      ifile.open(“data2”);		// open a file “data2” for read only

Example: Write a program to open a file using constructor & write a character in a file using write() function

int main() {
    ofstream f("E:\x.txt", ios::out); // open a file “x.txt” in a write mode
    char a;
    cout << "enter a character = ";
    cin >> a;
    f.write((char * ) & a, sizeof(a)); // write a character in file “x.txt”
    f.close(); // close a file
    return 0;
}

Output

 
enter a character=   x (Entered in console)


File x.txt
x

Note: In the above program, we are opening a file x.txt which is exists in an E drive with the help of ofstream class object (f).

After that we will enter character (x) in a console and and write the entered character in a file using wrire() function.   Then we will close a file by using close () function.

Use of read() and write() function 

“read () and write()” functions are used  to performs the reading and writing operation in a file in a binary format.

The format of read() and write() function are as follows:  

read( (char*)&p , sizeof(p) );  

write( (char*)&p , sizeof(p) );           

These function receives two argument. The first argument is the address of the variable P and the second argument is the size of variable P in byte.

Example: Write a program to open a file using open () function & write a character in a file using write () function.

int main() {
    ofstream f;
    char a;
    f.open("E: \x.txt", ios::app); // open file ”x.txt” from E drive
    cout << "enter a character=";
    cin >> a;
    f.write((char * ) & a, sizeof(a)); // write a character in file “x.txt”
    f.close(); // close a file
}

Output

 
enter a character=   x (Entered in console)


File x.txt
x

Note: In the above program, we are opening a file x.txt which is exists in an E drive with the help of ofstream class object (f).

After that we will enter character (x) in a console and write the entered character in a file using wrire() function.  

Then we will close a file by using close () function.       

Example: Write a program read a character in a file using read () function.

int main() {
    ifstream f;
    char a;
    f.open(“E: \x.txt”, ios:: in ); // open file ”x.txt” from E drive 
    f.read((char * ) & a, sizeof(a)); // read a character from file “x.txt”	
    cout << ”character = ” << a; // write a char in a console 
}

Output

 
character=   a (console)


File x.txt
ascdef

Note: In the above program, we are opening a file x.txt which is exist in a E drive.

After that we will read a  character (a) from a file “x.txt” and write that character in a console.     

Example: Write a program write and read a character in a file using read () & write () function. Use ifstream and ofstream class.

int main() {
    ofstream f;
    char a;
    f.open("E: \x.txt", ios::app); // open file ”x.txt” from E drive in write mode 	
    cout << "enter a character";
    cin >> a; // enter a character by user        
    f.write((char * ) & a, sizeof(a)); // write a character in file “x.txt”     
    f.close(); //close a file x.txt                    			
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive        	
    f1.read((char * ) & a, sizeof(a)); // read a character from file “x.txt”
    cout << "character = " << a; // write a char in a console
}

Output

 
enter a character=   s 
character = s


File Contains(s.txt)
s

Note: In the above program, we are opening a file x.txt which is exists in a E drive with the help of ofstream class object (f).

After that we will enter character (s) in a console and write the entered character in a file using wrire() function.

Then we will close a file by using close () function.    

Again we will open a x.txt file with the help of ifstream class object (f1) and read a character (s) from a file and write that character in a console.     

 Example:  Write a program to write and read a character in a file using read () & write () function. Use fstream class.

int main() {
    fstream f;
    char a;
    f.open("E: \x.txt", ios::app); // open file ”x.txt” from E drive				
    cout << "Enter a character = ";
    cin >> a; // enter a character by user        			
    f.write((char * ) & a, sizeof(a)); // write a character in file “x.txt”     
    f.close(); //close a file x.txt    
    f.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive       
    f.read((char * ) & a, sizeof(a)); // read a character from file “x.txt”
    cout << "Character = " << a; // write a char in a console 
    f.close(); //close a file x.txt

}

Output

 
enter a character= 											s 											character =s

Example: Write a program to write a string in a file using write () function.

int main() {
    ofstream f;
    char a[50];
    f.open("E: \x.txt", ios::app); // open file ”x.txt” from E drive		
    cout << "Enter a string";
    cin >> a; // string enter by user
    f.write((char * ) & a, sizeof(a)); // write an entered string in file “x.txt”
    f.close(); //close a file x.txt  
}

Output

 
Enter a string=
monu 


File Contains(s.txt)
monu

Example:  Write a program to read a string in a file using  read() function.

int main() {
    ifstream f;
    char a[50];
    f.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive   
    f.read((char * ) & a, sizeof(a)); // read a string from file “x.txt”
    cout << "string = " << a; // write a string in a console 					

}

Output

 
string=  this                    (console)


File Contains(s.txt)
this is my book

Note:  Assume in a file “x.txt”, ”this is my book” is written. Then read () function will read only first string (this) or first 50 character string.

Example: Write a program to write and read a integer data in a file using read() & write() function. use ifstream and ofstream class.

int main() {
    ofstream f;
    int a;
    f.open("E: \x.txt", ios::app); // open file ”x.txt” from E drive
    cout << "enter a integer data";
    cin >> a; // enter integer by user 
    f.write((char * ) & a, sizeof(a)); // write a integer in file “x.txt”     
    f.close(); //close a file x.txt                    			
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive        
    f1.read((char * ) & a, sizeof(a)); // read a integer data from file “x.txt”	
    cout << "integer = " << a; // write a integer in a console            			
}

Output

 
enter a integer data =  5
integer = 5                    (console)


File Contains(s.txt)
5

Example: Write a program to write in a file using  ofstream object.

 int main() {
     ofstream f; // create an object ‘f ’of ofstream   
     f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive in write mode	
     f << "aaaa bbbb cccc"; // write a statement in file “x.txt”			
     f << "\n xxxx yyyy zzzz"; // write a statement in file “x.txt”
     f.close(); //close a file x.txt    	                		
 }

Output

 
File Contains(s.txt)
aaaa bbbb cccc 
xxxx yyyy zzzz

Example: Write a program to write and read in a file using ofstream & ifstream object.

int main() {
    char a[20];
    ofstream f; // create an object ‘f ’of ofstream 
    f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive				
    f << "aaaa bbbb cccc"; // write a statement in file “x.txt”
    f << "\n xxxx yyyy zzzz"; // write a statement in file “x.txt”	
    f.close(); //close a file x.txt    				
    ifstream f1; // create an object ‘f1 ’of ifstream
    f1.open(“E: \x.txt”, ios:: in ); // open file ”x.txt” from E drive     
    f1 >> a; // read a string from file
    cout << a; // write in a console				
}

Output

 
aaaa                 (console)


File Contains(x.txt)
aaaa bbbb cccc
xxxx yyyy zzzz

Note: In the above program, statement (f1>>a) will read only string “aaaa” from a file.  If we will again read string using ifstream object f1 then for example

f1>>a;			// read a string from file					                                            cout<>a;  			// read a string from file							        cout<



Output

 
  aaaabbbb

Find End Of File (EOF)

We can find the end of file by using the eof() function.

The eof() function returns the non-zero value when end of file is detected, otherwise eof() function returns zero.

Example:  Write a program to write and read in a file & display the content of file. Use eof() function.

int main() {
    char a[20];
    ofstream f;
    f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive				
    f << "aaaa bbbb cccc"; // write a statement in file “x.txt”	
    f << "\n xxxx yyyy zzzz"; // write a statement in file “x.txt”	
    f.close(); //close a file x.txt    				
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive       
    while (f1.eof() == 0) //eof() return 0 if end not detected 		
    {
        f1 >> a; // read a string from file					
        cout << a; // write in a console		
    }
}

Output

 
aaaabbbbccccxxxxyyyyzzzz                (console)


File Contains(x.txt)
aaaa bbbb cccc  xxxx yyyy zzzz

Note: In the above program, statement               

while (f1.eof() == 0) //eof() return 0 if end not detected	
{
    f1 >> a; // read a string from file		
    cout << a; // write in a console
}

Initially function eof() return zero and condition will be true.

Then we will read a data from a file and print it in a console.

When function eof() detect the end of file then it will return non-zero value and then condition will be false and while loops terminates. 

 FILE POINTERS AND THEIR MANIPULATION

In a C++ file pointer is used to point to the reading or writing locations within a stream. There are  following member functions of file pointer

Function Description

seekg()

moves pointer to a specified location in write mode

seekp()

moves  pointer to a specified location in read mode

tellp()

gives current position of the pointer  for write

tellg()

gives current position of the pointer for read

Use of tellg()and tellp() functions

tellg() – gives current position of the pointer  for write

tellp() – gives current position of the pointer for read    

Example: Write a program to show the use of tellg() & tellp() function.  

Or

Write a program to show the present position of input and output pointer using tellg() & tellp().

int main() {
    char a[20];
    int loc;
    ofstream f;
    f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive in write mode	
    loc = f.tellp(); //  provides present position of output file pointer (0)
    cout << "position of o / p pointer = " << loc; // present position is 0		
    f << "aaaa bbbb cccc"; // write a statement in file “x.txt”
    loc = f.tellp(); //  provides present position of output file pointer (14)	
    cout << "after writing position of o / p pointer = " << loc; // present position is 14	
    f.close(); //close a file x.txt    				
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive in read mode     
    loc = f.tellg(); //  provides present position of input file pointer (0) 
    cout << "position of i / p pointer = " << loc; // present position is 0	  
    while (f1.eof() == 0) {
        f1 >> a; // read a string from file
    }
    loc = f.tellg(); //  provides present position of input file pointer (14) 	
    cout << "after reading position of o / p pointer = "<< loc; // present position is 14	 
    f1.close();
}

Output

 
position of o/p pointer= 0                                 after writing position of o/p pointer= 14                              position of i/p pointer=  0                                                after reading position of o/p pointer=14    
           (console)


File Contains(x.txt)
aaaa bbbb cccc  

Use of seekg()and seekp() functions

Function

Description

seekg()

moves pointer to a specified location in write mode

seekp()

moves pointer to a specified location in read mode

seekg() and seekp() function have a  two arguments. Their  format is fellows:-  

  seekg( offset , pre_position );  

seekp( offset , pre_position ); 

first argument specifies the number of bites the file pointer is to be shifted from the pre_position of the pointer.        

The pre_position may have one of the following possible values:-     

pre_position

Description

ios :: beg

Beginning of the file

ios :: cur

Current position of the file pointer

ios :: end

End of the file

File Pointer With Its Arguments in a seekg() function

Seek Option

Working

seekg(0,ios :: beg );

Go to the beginning of the file.

seekg(0,ios :: cur );

Rest at the current position.

seekg(0,ios :: end );

Go to the end of the file.

seekg(n,ios :: beg );

Shift file pointer to n+1 byte in the file.

seekg(n,ios :: cur );

Go front by n byte from current position.

seekg(-n,ios :: cur );

Go back by n byte from the present position.

seekg(-n,ios :: end );

Go back by n byte from the end of position.

Example: Write a program to enter text and again second time re-enter text from beginning position and replace the first word and display the content after 10 byte of the file pointer from the beginning of the file. 

Or

Write a program to show the use of seekp() and seekg() function.

int main() {
    char a[20];
    ofstream f;
    f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive in write mode	
    f << "aaaa bbbb cccc"; // write a statement in file “x.txt”		
    f.seekp(0, ios::beg); // Go to the beginning of the file.	
    f << "xxxx"; // write a statement in file “x.txt”
    f.close(); //close a file x.txt    				
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive      	
    f1.seekg(10, ios::beg); // Shift file pointer to 10 byte in the file	  	    
    while (f1.eof() == 0) {
        f1 >> a; // read a string from file
        cout << a; // write in a console
    }
    f1.close();
}

Output

 
cccc             (console)


File Contains(x.txt)
xxxx bbbb cccc

Note: In the above program, first, we write statement “aaaa bbbb cccc” then we  will shift the output  file pointer by using seekp() function  (f.seekp(0, ios :: beg);)at the beginning of the file and again write statement ”xxxx” in place of “aaaa”. 

Now the new statement/new content of file is “xxxx bbbb cccc”.

During reading file first we move the input file pointer 10 byte in a forward direction by using seekg() function (f1.seekg(10, ios :: beg);)   then we will read file till end of file.

Example: Write a program using seekg() to achive the following:   

  •  To move the pointer by 15 position.
  • To go backward by 20 byte from the end.
  • To go byte 50 in the file.

First code is

#include 

using namespace std;

int main() {
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive for read
    f1.seekg(15, ios::cur); // Shift file pointer to 15th byte in the file	  	       
    while (f1.eof() == 0) {
        f1 >> a; // read a string from file
        cout << a; // write in a console	
    }
    f1.close();
}

Second code is

#include 

using namespace std;

int main() {
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive      	
    f1.seekg(-20, ios::end); // Shift file pointer back to 20 byte from end of file
    while (f1.eof() == 0) {
        f1 >> a; // read a string from file	
        cout << a; // write in a console
    }
    f1.close();
}

Third is

#include 

using namespace std;

 int main() {
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive  
    f1.seekg(50, ios::bg); // Shift file pointer to 50 byte in the file	  	  
    while (f1.eof() == 0) {
        f1 >> a; // read a string from file	
        cout << a; // write in a console
    }
    f1.close();
}

Example:  Write a program to copy the content of one file into another file.

int main() {
    char a[20];
    ofstream f;
    f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive					
    f << "aaaa bbbb cccc"; // write a statement in file “x.txt”
    f.close(); //close a file x.txt    				
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive      		
    ofstream f2;
    f2.open("E: \xyz.txt", ios::out); //  open file ”xyz.txt” from E drive      	                	
    while (f1.eof() == 0) {
        f1 >> a; // read a string from file x.txt
        f2 << a; // write in a file xyz.txt	
    }
    f1.close();
}

Output

 
aaaa bbbb cccc            (file x.txt)


aaaa bbbb cccc            (file xyz.txt)

Use of put() and get() function

get()” is a member function of the class fstream. This function reads the single character from a file.

“put()” function is a member of fstream class. The put() function write a single character in the file.

Example: Write a program to write and read the characters in a file using put() & get() function.

#include 

using namespace std;

int main() {
    char a;
    ofstream f;
    f.open("E: \x.txt", ios::out);
    cout << "enter character = ";
    cin >> a; // character entered by user in console
    f.put(a); //  read console & write a character in file “x.txt”		
    f.close(); //close a file x.txt    				
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive     	
    f1.get(a); //  read a single character from file 	 	
    cout << "character = " << a;
    f1.close();
}

Output

 
Enter character=  s               
character = s            (console)


s          (file x.txt)

Example: Write a program to write and read five characters in a file using put() & get() function.

#include 

using namespace std;

int main() {
    char a;
    ofstream f;
    f.open("E: \x.txt", ios::out);
    cout << "enter character = ";
    for (int i = 1; i <= 5; i++) {
        cin >> a;
        f.put(a); // write a character in file “x.txt”	
    }
    f.close(); //close a file x.txt    				
    ifstream f1;
    f1.open("E: \x.txt", ios:: in ); // open file ”x.txt” from E drive 
    cout << "character = ";
    for (int i = 1; i <= 5; i++) {
        f1.get(a); //  read the character from file
        cout << a;
    }
    f1.close();
}

Output

 
enter character = x                                           y				                  z				                   q                        				  u  			                        
character = xyzqu        (console)


xyzqu           (file x.txt)

Use of fail() function

“fail()” stream state member function is used to check whether a file has been opened for input or output successfully or not.

 It returns the non-zero value if an operation is unsuccessful(or file is not opened) and return zero when it is open.

#include 

using namespace std;

int main() {
    ofstream f;
    f.open("E: \x.txt", ios::out); // open file ”x.txt” from E drive for write	
    if (f.fail() == 0) //fail() return 0 when file is open
    {
        f << "aaaa bbbb cccc"; // write a statement in file “x.txt”
        f.close(); //close a file x.txt 	
    } else {
        cout << "file is not opened.";
    }

}

Output

 
aaaa bbbb cccc        (file x.txt)

Note: In the above program, fail() return 0 when file is open and condition will be true after that we can perform operation and return non-zero  value  when file is not open and condition will be false.

Categories C++