File Handling In C++

Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and to perform various operations on it.

A stream is an abstraction that represents a device on which operations of input and output are performed. A stream can be represented as a source or destination of characters of indefinite length depending on its usage.

In C++ we have a set of file handling methods. These include ifstream, ofstream, and fstream. These classes are derived from fstrembase and from the corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and therefore we must include fstream and therefore we must include this file in any program that uses files.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.

  • ofstream: This Stream class signifies the output file stream and is applied to create files for writing information to files
  • ifstream: This Stream class signifies the input file stream and is applied for reading information from files
  • fstream: This Stream class can be used for both read and write from/to files.

All the above three classes are derived from fstreambase and from the corresponding iostream class and they are designed specifically to manage disk files.
C++ provides us with the following operations in File Handling:

  • Creating a file: open()
  • Reading data: read()
  • Writing new data: write()
  • Closing a file: close()

Moving on with article on File Handling in C++

Opening a File

Generally, the first operation performed on an object of one of these classes is to associate it to a real file. This procedure is known to open a file.

We can open a file using any one of the following methods:
1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.

To open a file use

1
open() function

Syntax

1
void open(const char* file_name,ios::openmode mode);

Here, the first argument of the open function defines the name and format of the file with the address of the file.

Example of opening/creating a file using the open() function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out); 
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}