C++ File Handling

C++ File handling is used to store, input, and output data permanently on secondary memory.
Normally, program data are stored in variables. When the program execution ends all the stored data and computational results are destroyed because data in variables are temporary.
The user has to input data each time when the program executes which refers to wastage of time.


Three types of streams are associated with C++ file handling, input stream, output stream, and both input/ output stream. These are given below.

cpp file handling
  1. Ifstream: Used to take input from the file
  2. ofstream: Used to create and write on the file
  3. fstream: Used for both input and output from/to file

Write to a file

For this purpose, You can use “fstream” or “ofstream” input streams. Below is the code where we use ofstream to create and write records in the text file.

//file handling in C++
#include <iostream>
#include <fstream>
using namespace std;

int main() {

  ofstream Write_to_File("myFile.txt");

  Write_to_File << "My name is: John Smith";

  Write_to_File.close();
}

Output

Now you can open the file and check the record

My name is: John Smith

Read from a file

Here we use the “ifstream” output stream to read records from the text file and display them on the console.

//File handling in C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {


  string fileText;

  ifstream Read_From_File("myFile.txt");

  while (getline (Read_From_File, fileText)) {
    cout << fileText;
  }

  Read_From_File.close();
}

Output

Below is the output after reading the file.

My name is: John Smith

Recommended Articles

C++ student grade program

C++ program to print star patterns

Scroll to Top