TutorialStudyMite

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

GGarvit Gulati1 min read
Beginner friendly

Track completion, mastery, and revision.

# 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;

    // Open in write mode
    ob.open("test.txt", ios::out);
    ob << "hello world\n";
    ob << "this is my first file";
    ob.close();

    // Open in read mode
    ob.open("test.txt", ios::in);
    string str;
    while (ob >> str) { 
        cout << str << "\n";
    }
    ob.close();

    return 0;
}

Output

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.