C++ File Handling

In C++, for working with files we use the fstream library. For using the fstream library include both and header files.

Example:

#include<iostream>

#include<fstream>

fstream library includes three classes, which are used to create, write or read files:

ofstream: This class is used to create and write the files. 

ifstream:  This class is used to read the files 

fstream:   This class is used for both reading and writing the files. 

Creating and Writing a file:

  • For creating a file, use either ofstream or fstream class, and specify the name of the file.
  • For writing the file, use the insertion operator(<<).
//Program for creating and writing file:
 
#include <iostream>
#include <fstream>
using namespace std;
 
int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");
 
  // Write to the file
  MyFile << "This is the First file by me!";
 
  // Close the file
  MyFile.close();
  // Closing file can clean up unnecessary space, and it is a good practice too.
}

Reading a File:

  • For creating a file, use either ofstream or fstream class, and specify the name of the file.
  • We will use a while loop together with the getline() function (which belongs to the ifstream class) to read the file line by line, and to print the content of the file.
//Program for Reading file:
 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
int main () {
  // Create a text file
  ofstream MyWriteFile("filename.txt");
 
  // Write to the file
  MyWriteFile << "Files can be tricky, but it is fun enough!";
 
  // Close the file
  MyWriteFile.close();
 
  // Create a text string, which is used to output the text file
  string myText;
 
  // Read from the text file
  ifstream MyReadFile("filename.txt");
 
  // Use a while loop together with the getline() function to read the file line by line
  while (getline (MyReadFile, myText)) {
    // Output the text from the file
    cout << myText;
  }
 
  // Close the file
  MyReadFile.close();
}