Site Tools


wiki: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.

Example

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;
}
wiki/hpp-fstream.md · Last modified: by 127.0.0.1