Thuta Learning
AdvancedProgrammingbeginner

File I/O

Relax. We'll talk through this in plain words — no textbook voice.

File I/O is about a program writing to files and reading data from them. It's useful for saving settings, generating reports, writing log files, and reading CSV data. C++ uses the <fstream> library for this.

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

int main() {
    ofstream outFile("lesson.txt");

    if (!outFile) {
        cout << "Could not create file.";
        return 1;
    }

    outFile << "C++ file handling is useful.";
    outFile.close();

    ifstream inFile("lesson.txt");
    string line;

    if (getline(inFile, line)) {
        cout << line;
    }

    inFile.close();
    return 0;
}

ofstream is used to write to a file, and ifstream is used to read from one. Since opening a file can fail, it's checked with if (!outFile). getline() reads a single line at a time.

You should see
C++ file handling is useful.

Info

A wrong file path or missing permissions can make a file operation fail. In real projects, always check whether opening a file succeeded or failed.

Easy traps

  • Reading a file right after writing to it without closing it first may not give you the expected result in some environments. Be sure to use close() or careful scope control.