Unit 5: Standard Template Library (STL) & Advanced ConceptsLesson #18 / 20

Lesson 18: File I/O Handling in C++: std::ifstream & std::ofstream

NSNextSemLast Updated: 5 Aug, 2026

📁 File Streams & Disk I/O on ⊞ Windows 11

File operations in C++ are handled via the <fstream> header:

  • 📥 std::ifstream: Read input from files.
  • 📤 std::ofstream: Write output to files.
  • 🔄 std::fstream: Read and write bidirectional file streams.

  • 💻 Code Example: Writing and Reading Config Files

    C++ Source Code (main.cpp)
    #include <iostream>
    #include <fstream>
    #include <string>
    int main() {
    // 1. Write to file
    std::ofstream outFile("config.txt");
    if (outFile.is_open()) {
    outFile << "AppName=NextSem_CPP_Engine
    ";
    outFile << "Version=2026.1.0
    ";
    outFile << "TargetOS=Windows_11
    ";
    outFile.close();
    std::cout << "✅ Configuration written to config.txt" << std::endl;
    }
    // 2. Read back from file
    std::ifstream inFile("config.txt");
    std::string line;
    std::cout << "
    --- Reading config.txt ---" << std::endl;
    while (std::getline(inFile, line)) {
    std::cout << line << std::endl;
    }
    inFile.close();
    return 0;
    }
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    Interactive Knowledge Check

    Test your understanding of Lesson #18 concepts

    Which C++ file stream class is used specifically for READING data from a disk file?