Program to read and write to a file in C++

Written by

Garvit Gulati

# Understanding the question

In this program, we have to create a file, write something to that file, and then extract that data from that file and print it on our screen.

# Approaching the question

  1. To process a file in C++, we can use the functions provided in the <fstream> header file. This includes functions for opening, reading, and writing to text files.
  2. Follow these steps to process a file:
    1. Open the file: Use the open() function and specify the mode (e.g. ios::in, ios::out) to tell the compiler whether to read from or write to the file.
    2. Work on the file: Use the appropriate functions to read and write to the file as needed.
    3. Close the file: After you have finished working with the file, be sure to close it before terminating the program.
  3. To write to a file, you can use the cascade operator (<<) or the put() function to write character by character.
  4. To read from a file, you can use the cascade operator (>>) to read word by word, or use the getline() function to read line by line and the getchar() function to read character by character.
  5. Note that the <fstream> header file is a superset of <iostream>, so you don't need to include <iostream> separately.

Code

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

int main() {
  fstream ob;

  ob.open("test.txt", ios::out);  // opening file in writing mode

  ob << "hello world\n";  // writing data to file

  ob << "this is my first file";

  ob.close();  // closing the file

  ob.open("test.txt", ios::in);  // again opening the file but in reading mode

  while (!ob.eof()) {
    string str;

    ob >> str;  // reading word by word from file and storing in str

    cout << str << "\n";  // printing str
  }

  ob.close();  // closing the file after use

  return 0;
}

Output

Program to read and write to a file in C++