0Pricing
C++ Academy · Lesson

Reading Files with ifstream

Read text and data.

What Is ifstream?

std::ifstream (input file stream) reads data from files. It behaves like std::cin but its source is a file on disk.

  • Defined in <fstream>.
  • Opens a file by name in its constructor.
#include <iostream>
#include <fstream>

int main() {
    std::ofstream("demo.txt") << "hello\n";
    std::ifstream in("demo.txt");
    std::string word;
    in >> word;
    std::cout << word << '\n';
    return 0;
}

Opening a File

Construct an ifstream with a filename, then check with is_open() whether the file was found.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("data.txt") << "42\n";
    std::ifstream in("data.txt");
    std::cout << (in.is_open() ? "opened" : "failed") << '\n';
    return 0;
}

All lessons in this course

  1. Reading Files with ifstream
  2. Writing Files with ofstream
  3. Binary File I/O
  4. Error Handling and State
← Back to C++ Academy