How File Handling Works in C++

Introduction

C++ provides us with various inbuilt functions using which we can easily deal with files. File handling refers to storing some information permanently on the disk space (or Hard disk). File handling can be achieved in any programming language using the following steps:

  • Name a file
  • Open a file
  • Write the required data into the file
  • Read data from a file
  • Close a file after the required operation

Streams in C++

Stream is defined as the sequence of bytes passed as input to a program that is being executed and then it returns again a sequence of bytes as an output.  In simple words, we can say that a stream is a flow of information in the form of sequences.

The executing program interacts with the input/output devices and performs operations. Such operations are known as console I/O operations. Similarly, the executing program interacts with the files and performs input and output operations, and such operations are known as “disk I/O operations”.

Inbuilt classes for File stream operations

In C++, the input/output system provides us with a number of classes that contains file-handling methods. These classes are the listed below:

  • ifstream
  • ofstream
  • Fstream

These classes are defined under the fstream header file. We use ifstream class to read data from files, ofstream class to write data into files, fstream class in order to perform both the operations, read from and write into files.

Now the primary steps before reading or writing into files is to open a file. A file can be opened using one of the following ways in C++:

  • During object creating, give the file name to the constructor.
  • Open file using open method.

All these methods have the following structure:

Constructor method to open a file:

ifstream (nameOfFile, modeOfOpening);
ifstream fin(nameOfFile, modeOfOpening) by default modeOfOpening = ios::in
ifstream fin("nameOfFile");

Open method to open a file:

ifstream fin;
fin.open(nameOfFile, modeOfOpening)
fin.open("nameOfFile"); 

Parameters:

Here the nameOfFile denotes the name of the file to be opened and mode is one of the following:

Constant

Description

Instruction

in

input

Open file to read

out

output

Open file for writing 

binary

binary

Execute instruction in binary mode

trunc

truncate

Any file content that exist in the file before it was open are ignored

The default file opening modes of ifstream, ofstream, and fstream are the following:

ifstream

ios::in

ofstream

ios::out

fstream

Ios:: in/out

Now let us consider a program that illustrates the working of ifstream and ofstream class:

Source Code

#include <iostream>

#include<fstream>

using namespace std;


int main()
{

// Create an object of ofstream class
    ofstream fout;

//  Create a string object
    string currentLine;

    /*
    The ios::out mode, automatically discards if any
    content is present in the file
    */
    fout.open("sample.txt");

    // If we are able open the file successfully
    // then execute a loop
    while (fout) {

        // Read a Line from standard input
        getline(cin, line);

        // Press -1 to stop reading further
        if (currentLine == "-1")
            break;

        // Write line in file
        fout << currentLine << endl;
    }

    // Close the File
    fout.close();

    // Create an object of ifstream class
    ifstream fin;

    // The default open mode is ios::in
    fin.open("sample.txt");

    // Loop till EOF (End of File) is reached
    while (getline(fin, currentLine)) {
     
        // Print line (read from file) in console
        cout << currentLine << endl;
    }

    // Close the file
    fin.close();


    return 0;
}

write your code here: Coding Playground


Input:

Board Infinity

-1

Output:

“sample.txt”

Output Description:

As you can see in the output, We have input the string “Board Infinity” from the user and written the same in the “sample.txt” file.

Now let us consider a program that illustrates the working of fstream class:

Source Code

#include <iostream>
#include<fstream>
using namespace std;
int main() {

// Create an object of fstream class
fstream fobject;

// Declare a string
    string currentLine;

    // By default the file openmode is ios::in|ios::out mode
    // It overwrites the content of file
  fobject.open("sample.txt", ios::trunc | ios::out | ios::in);

    // Execute a loop If file successfully Opened
    while (fobject) {

        // Read a line from standard input
        getline(cin, currentLine);

        // Press -1 to break the loop
        if (currentLine == "-1")
            break;

        // Write the line into file
      fobject << currentLine << endl;
    }

    // Run a loop till EOF (End of File) is occured
    // Point read pointer at beginning of the file
    fobject.seekg(0, ios::beg);

    while (fobject) {

        // Read a Line from File
        getline(fobject, currentLine);

        // Print line in Console
        cout << currentLine << endl;
    }

    // Close the file
    fobject.close();


    return 0;
}

Input:

Board Infinity

-1

Output:

“sample.txt”

Output Description

As you can see in the output, We have input the string “Board Infinity” from the user and written the same in the “sample.txt” file.

Conclusion

In this article, we discussed how file handling can be done using objects in C++. We saw the working of the classes: fstream, ofstream, ifstream. We believe that this article has surely helped you to enhance your knowledge of file handling in C++.