Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::fstream: bidirectional file stream

std::fstream connects character input and output to a named file while retaining formatting and stream-error state.

Version: C++23

Syntax

using std::fstream = std::basic_fstream<char>;

explicit std::fstream(const char* path,
    std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out);
explicit std::fstream(const std::string& path,
    std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out);

void open(const std::filesystem::path& path,
    std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out);
void close();
bool is_open() const;

std::fstream from <fstream> is the std::basic_fstream<char> alias and inherits input and output operations from std::basic_iostream. Its contained std::basic_filebuf associates the stream with a named file. The constructor and open request std::ios::in | std::ios::out by default; explicit flags such as std::ios::trunc, std::ios::app, and std::ios::binary determine the opening mode.

The example opens a file for input and output with std::ios::trunc, writes 42 blue, flushes the output buffer with flush, moves the input position to the beginning with seekg(0), and extracts a number and a word. It therefore prints 42 blue. The block scope closes the stream before std::filesystem::remove; production code should also diagnose closing failures or enable exceptions for selected state bits.

An unsuccessful open sets failbit; is_open() reports only the file-buffer association, whereas operator bool, fail(), and bad() report operation state. std::ios_base::failure is thrown only for bits enabled in exceptions(). After reaching EOF, clear the state before seeking again, and when switching between writing and reading use explicit flush plus seekg/seekp so buffered positions are unambiguous. The stream is movable but not copyable. Text mode may translate line endings, so binary data requires std::ios::binary.

Examples

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

int main() {
    const std::filesystem::path path = "cpp-ref-014-fstream.txt";
    {
        std::fstream file(path, std::ios::in | std::ios::out | std::ios::trunc);
        if (!file) return 1;
        file << 42 << ' ' << "blue";
        file.flush();
        file.seekg(0);

        int number{};
        std::string word;
        file >> number >> word;
        if (!file) return 2;
        std::cout << number << ' ' << word << '\n';
    }
    std::filesystem::remove(path);
}

Result

42 blue

std::fstream → 42 blue

Sources