C++:
Reading a text file

How to:

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

int main() {
    std::ifstream file("example.txt");
    std::string line;

    if (file.is_open()) {
        while (getline(file, line)) {
            std::cout << line << '\n';
        }
        file.close();
    } else {
        std::cout << "Unable to open file";
    }
    
    return 0;
}

If example.txt contains:

Hello, world!
This is a test file.

The output will be:

Hello, world!
This is a test file.

Deep Dive

Back in the day, data storage and retrieval were pretty cumbersome. With the advent of higher-level programming languages, operations like reading from a text file became simpler. C++ offers several ways to read from files, leveraging input/output streams provided by the standard library.

Alternatives to for file I/O include using older C functions (like fopen, fgets, etc.), operating system-specific APIs, or other libraries that abstract away some of the lower-level details.

When we talk about implementation details, it’s essential to know that std::ifstream is a class that handles input file streams. The key functions involved are is_open() to check if the file stream was successfully opened, getline() to read the file line by line, and close() to close the file stream. It’s crucial to manage file resources correctly to avoid leaks or data corruption. Luckily, modern C++ (C++11 and later) includes features like RAII, which can handle resource management more safely through object lifetimes.

See Also