Site Tools


hpp-fstream

Table of Contents

<fstream>

<fstream> provides std::ifstream (input), std::ofstream (output), and std::fstream (bidirectional) for file I/O. They wrap C's FILE* with the iostream interface, handling mode flags and automatic cleanup via RAII. Use it for all file reading and writing; avoid fopen / fclose in C++ code.

This example writes text to a file and then reads it back using ofstream and ifstream with automatic resource management.

// compile: g++ -std=c++11 -o fstreamexample fstreamexample.cpp
// run: ./fstreamexample
// description: write and read a file

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ofstream out("test.txt");
    out << "hello world\n";
    out.close();
    
    std::ifstream in("test.txt");
    std::string line;
    while (std::getline(in, line)) {
        std::cout << "read: " << line << "\n";
    }
    
    return 0;
}
hpp-fstream.md · Last modified: