Labs ICT
โญ Pro Login

Read & Write Files

Reading and Writing Files

Use ofstream to write data to a file and ifstream to read data back. Always close the file after operations are complete.

Writing to a File

Use the insertion operator << with an ofstream object.

Reading from a File

Use getline() to read line by line, or the extraction operator >> for tokenized input.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
  ofstream out("data.txt");
  out << "Line one\nLine two\nLine three\n";
  out.close();

  ifstream in("data.txt");
  string line;
  while (getline(in, line)) {
    cout << line << "\n";
  }
  in.close();
  return 0;
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which class is used to read from files in C++?