Reading Files & EOF
Overview
Writing data is easy; reading it back in is structurally harder. You don't know how long the file is, and reading past the end of the file crashes the stream.
To read a file, we use `std::ifstream` (Input File Stream). Just like cin pulls data from the keyboard, ifstream pulls data from the file. To prevent crashing when the file ends, we use a while loop combined with the EOF (End Of File) flag, or we utilize the std::getline() function which automatically returns false the exact moment the file is empty.
Syntax
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 1. IFSTREAM (Input File Stream)
std::ifstream myFile("database.txt");
std::string line;
if (myFile.is_open()) {
// 2. The getline() loop!
// This function attempts to read a full line of text.
// If it successfully reads a line, it returns TRUE.
// If it hits the end of the file, it returns FALSE and safely stops the loop!
while (std::getline(myFile, line)) {
std::cout << "Read from disk: " << line << "\n";
}
myFile.close();
} else {
std::cout << "Error: File does not exist!\n";
}
return 0;
}Common Pitfalls
- Using
myFile >> stringVariableinstead ofgetline. If you use the standard extraction operator (>>), it fundamentally stops reading the exact moment it hits a 'Space' character. If your file contains "Hello World", it will only read "Hello".getline()is mandatory to read entire sentences.
Interview Questions
std::ios::app flag do when opening an Output File Stream?By default, when you open an ofstream, C++ violently deletes the existing file and creates a brand new blank one. If you want to keep the old data and simply add new data to the bottom (like a constantly running Error Log), you must open the file in 'Append Mode' using std::ofstream file("log.txt", std::ios::app);.
Real-World Example
Parsing a CSV (Comma Separated Values) file dynamically using input streams.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream csv("data.csv");
std::string value;
if (csv.is_open()) {
// We overload getline() with a 3rd parameter!
// It tells the function to stop reading when it hits a Comma (',') instead of a Newline!
while (std::getline(csv, value, ',')) {
std::cout << "Parsed Cell: " << value << "\n";
}
csv.close();
}
return 0;
}Check Your Knowledge
Test your understanding of Reading Files & EOF with these quick questions.