ReviseAlgo Logo

File I/O

Reading Files

Read data from files using std::ifstream, manage stream states, and choose extraction methods.

Interview: Handling file streams, the eof() loop anti-pattern, buffer sizing, and standard stream error state validation.

Last Updated: June 13, 2026 8 min read

In C++, file input is managed using std::ifstream (input file stream) defined in the <fstream> header. Understanding how to manage stream states and read lines or tokens safely is vital for system programming.

std::ifstream

A stream class designed to read from files. It automatically closes the file when it goes out of scope (RAII).

Stream State

Check stream flags: good(), fail() (format errors), bad() (I/O loss), and eof().

Extraction Methods

Choose between line-based reading (std::getline) and token-based reading (extraction operator >>).

The EOF Loop Anti-Pattern

A common bug in C++ file reading is using while(!file.eof()). The EOF (End of File) flag is only set after a read operation attempts to fetch data past the end of the file and fails.

The Correct Approach

Always perform the read operation inside the loop condition itself. The stream evaluates to false when a read fails (due to EOF or corruption), terminating the loop cleanly: while (std::getline(file, line)) { /* process line */ }

Code Walkthrough

Demonstrates safe opening and line-by-line parsing of a text file.

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

void printFileContent(const std::string& filepath) { std::ifstream file(filepath);

if (!file.is_open()) { std::cerr << "Failed to open file: " << filepath << std::endl; return; }

std::string line; // Correct loop condition: checks stream health on each read while (std::getline(file, line)) { std::cout << line << std::endl; }

if (file.bad()) { std::cerr << "I/O error occurred while reading the file!" << std::endl; } // File closes automatically when ifstream goes out of scope }

int main() { printFileContent("config.txt"); return 0; }

Interview-Relevant Information

Q: What is the difference between stream.fail() and stream.bad()?
Answer: stream.fail() returns true for recoverable errors, such as format mismatches (e.g. trying to extract an integer but finding text). stream.bad() returns true for unrecoverable hardware or systems-level I/O failures (e.g. disk write failure or loss of connection).

Q: Does std::ifstream close files automatically?
Answer: Yes, std::ifstream's destructor automatically invokes close(). This follows the RAII (Resource Acquisition Is Initialization) design pattern, guaranteeing no resource leaks even if exceptions are thrown.

Quick Checklist

Did you check is_open()? Are you avoiding while (!file.eof())? If yes, your file reading is safe and idiomatic.

Use Cases

Parsing application configuration profiles (JSON, INI, custom syntax) on startup.

Reading structured comma-separated data (CSV) files into internal vectors.

Common Mistakes

Using while(!file.eof()), which processes the final line or token twice because EOF is only checked after a read failure.

Forgetting to check if the file opened successfully, leading to silent operation failures.