How to Read File Line by Line in C++: Simple Guide
In C++, you can read a file line by line using
std::ifstream to open the file and std::getline to read each line into a string. This method reads the file until the end, processing one line at a time.Syntax
To read a file line by line, you use std::ifstream to open the file and std::getline to read each line into a string variable. The loop continues until the file ends.
std::ifstream file("filename.txt"): Opens the file for reading.std::string line: Holds each line read from the file.std::getline(file, line): Reads one line from the file intoline.
cpp
std::ifstream file("filename.txt"); std::string line; while (std::getline(file, line)) { // process line }
Example
This example opens a file named example.txt and prints each line to the console. It shows how to safely open the file and read it line by line.
cpp
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream file("example.txt"); if (!file) { std::cerr << "Failed to open file." << std::endl; return 1; } std::string line; while (std::getline(file, line)) { std::cout << line << std::endl; } file.close(); return 0; }
Output
Hello, world!
This is a test file.
Reading line by line in C++.
Common Pitfalls
Common mistakes when reading files line by line include:
- Not checking if the file opened successfully before reading.
- Using
file >> lineinstead ofstd::getline, which reads only one word, not the whole line. - Not handling empty lines or end-of-file correctly.
Always check the file stream state and use std::getline for full lines.
cpp
/* Wrong way: reads only one word, not full line */ std::ifstream file("example.txt"); std::string line; while (file >> line) { std::cout << line << std::endl; // prints words, not lines } /* Right way: reads full lines */ file.clear(); file.seekg(0); while (std::getline(file, line)) { std::cout << line << std::endl; // prints full lines }
Quick Reference
Tips for reading files line by line in C++:
- Use
std::ifstreamto open files. - Use
std::getlineto read full lines. - Always check if the file opened successfully.
- Close the file after reading.
Key Takeaways
Use std::ifstream and std::getline to read files line by line in C++.
Always check if the file opened successfully before reading.
std::getline reads the entire line including spaces, unlike operator>>.
Close the file after finishing reading to free resources.
Handle empty lines and end-of-file conditions properly.