Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ifstream: input file stream

std::ifstream connects character input operations to a file and retains formatting, EOF, and error state.

Version: C++23

Syntax

using std::ifstream = std::basic_ifstream<char>;

explicit std::ifstream(const char* path,
    std::ios_base::openmode mode = std::ios_base::in);
explicit std::ifstream(const std::filesystem::path& path,
    std::ios_base::openmode mode = std::ios_base::in);

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

std::ifstream from <fstream> is the std::basic_ifstream<char> alias. It contains a std::basic_filebuf and inherits formatted and unformatted input from std::basic_istream. Its constructor or open adds std::ios::in to the requested mode; std::ios::binary disables platform text-mode translations where applicable. A std::filesystem::path can name the file.

The example first creates a file containing 12 cyan, then opens it through std::ifstream, extracts a number and a word, and prints 12 cyan. The if (!input) check validates extraction, and explicit close precedes file removal.

An unsuccessful open sets failbit; is_open() reports buffer association, while operator bool, fail(), bad(), and eof() report operation state. std::ios_base::failure is thrown only for bits enabled in exceptions(). After EOF, call clear() before seeking again when state blocks seekg. The stream is movable but not copyable. Its destructor closes the file, but use explicit close and inspect state when close failure must be diagnosed.

Examples

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

int main() {
    const std::filesystem::path path = "cpp-ref-015-ifstream.txt";
    {
        std::ofstream output(path);
        output << "12 cyan\n";
    }

    std::ifstream input(path);
    int number{};
    std::string word;
    input >> number >> word;
    if (!input) return 1;
    std::cout << number << ' ' << word << '\n';
    input.close();
    std::filesystem::remove(path);
}

Result

12 cyan

std::ifstream → 12 cyan

Sources