File Handling in C++

  • File handling is used to store a data permanently in computer. The data can be stored in secondary memory (hard disk) using file handling.
  • The I/O data can easily transferred from one computer to another by using files.
  • The C++ standard library provides fstream class for performing Read and Write operations.
The fstream defines three new datatypes are as:

DatatypeDescription
ofstreamUsed for creating a file and write data on files.
ifstreamUsed for reading the data from files.
fstreamUsed for both read and write data from files.

Following are the functions used in File Handling.

FunctionDescription
open()It is used to create a file.
close()It is used to close an existing file.
get()It is used to read a single unit character from a file.
put()It is used to write a single unit character in file.
read()It is used to read data from file.
write()It is used to write data into file.

Following are the operations of File Handling.
1. Naming a file
2. Opening a file
3. Reading data from file
4. Writing data into file
5. Closing a file

Opening a File

  • The open() function is used to open multiple files which uses the same stream object.
  • The fstream or ofstream object is used to open a file for writing and ifstream object is used to open a file for reading.
    Syntax:
    void open(const char *filename, ios::openmode mode);
    where,
    First argument *filename specifies the name of file and location.
    Second argument open() member function defines the mode in which the file should be opened.
Following are the file opening modes

File modeDescription
ios::outThis mode is opened for writing a file.
ios::inThis mode is opened for reading a file.
ios::appThis mode is opened for appending data to end-of-file.
ios::binaryThe file is opened in binary mode.
ios::ateThis file moves the pointer or cursor to the end of the file when it is opened.
ios::truncIf the file is already exists, using this mode the file contents will be truncated before opening the file.
ios::nocreateThis mode will cause to fail the open() function if the file does not exists.
ios::noreplaceThis mode will cause to fail the open function if the file is already exists.

All these above modes can be combined using the bitwise operator (|). for example, ios::out | ios::app | ios::binary

Closing a File

  • The close() function is used for closing a file.
  • When a program terminates, it automatically closes or flushes all the streams, releases all the allocated memory and closes all the opened files. But a good practice for programmer to close all the opened files before the program termination.
    Syntax:
    void close();
  • A file must be closed after completion of all operation related to a file.

Writing to a File

  • The insertion operator (<<) is used to write information in a file.
  • The ofstream or fstream object is used instead of cout object.

Reading from a File

  • The extraction operator (>>) is used to read information from a file into your program.
  • The ifstream or fstream object is used instead of cin object.

Input and Output Operation

Following functions are used for I/O Operation:

FunctionDescription
put()This function writes a single character to the associated stream.
get()This function reads a single character to the associated stream.
write()This function is used to write the binary data.
read()This function is used to read the binary data.

File Pointers

  • File pointer is associated with two pointers,
    1. Input pointer reads the content of a given file location.
    2. Output pointer writes the content to a given file location.
  • All Input/Output stream objects have at least one internal stream pointer.
  • The ifstream has a get pointer which points to the element to read in the next input operation.
  • The ofstream has a put pointer which points to the location where the next element has to be written.
  • The fstream inherits both the get and put pointers from iostream.
Following are the member function for manipulation of file pointer:

FunctionDescription
seekg()It moves the get pointer (input) to a specified location.
seekp()It moves the put pointer (output) to a specified location.
tellg()It gives the current position of the get pointer.
tellp()It gives the current position of the put pointer.

Example: Program demonstrating Read and Write mode of a file

Following program reads the information from the file and displays it onto the screen.

#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
   char name[50];

   ofstream ofile;                               // open a file in write mode.
   ofile.open("abc.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "<<endl;
   cin.getline(name, 50);
   cout<<endl;
   ofile << name << endl;            // write inputted data into the file.
   ofile.close();                              // close the opened file.

   ifstream ifile;                           // open a file in read mode.
   ifile.open("abc.dat");

   cout << "Reading from the file" << endl;
   ifile >> name;

   cout << name << endl;      // write the data at the screen.
   
   ifile.close();                       // close the opened file.

   return 0;
}


Output:
Writing to the file
Enter your name:
Prajakta Pandit

Reading from the file
Prajakta Pandit