Lesson 21 of 25

File Handling

Reading and Writing Files

C++ uses fstream for file operations — ifstream for reading, ofstream for writing, and fstream for both.

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

// Writing to a file
ofstream outFile("data.txt");
if (outFile.is_open()) {
    outFile << "Hello, File!" << endl;
    outFile << "Line 2" << endl;
    outFile.close();
}

// Reading from a file
ifstream inFile("data.txt");
string line;
if (inFile.is_open()) {
    while (getline(inFile, line)) {
        cout << line << endl;
    }
    inFile.close();
}

// Append to file
ofstream appendFile("data.txt", ios::app);
appendFile << "New line" << endl;
appendFile.close();

// Check if file exists
ifstream check("data.txt");
if (check.good()) {
    cout << "File exists" << endl;
}