How to Read File in C++: Simple Guide with Examples
To read a file in C++, use the
std::ifstream class from the <fstream> library. Open the file with ifstream.open() or by passing the filename to the constructor, then read its contents using methods like getline() or the extraction operator >>.Syntax
Here is the basic syntax to read a file in C++:
#include <fstream>: Include the file stream library.std::ifstream file("filename.txt");: Create an input file stream and open the file.if (file.is_open()): Check if the file opened successfully.std::getline(file, line);: Read a line from the file into a string variable.file.close();: Close the file when done.
cpp
#include <fstream> #include <string> int main() { std::ifstream file("filename.txt"); if (file.is_open()) { std::string line; while (std::getline(file, line)) { // process line } file.close(); } }
Example
This example reads a file named example.txt line by line and prints each line to the console.
cpp
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream file("example.txt"); if (!file) { std::cerr << "Unable 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 sample file.
Reading files in C++ is easy.
Common Pitfalls
Common mistakes when reading files in C++ include:
- Not checking if the file opened successfully before reading.
- Forgetting to include
<fstream>or<string>. - Using
while (!file.eof())which can cause reading the last line twice. - Not closing the file after finishing reading.
Always check file.is_open() or the file stream's boolean state before reading.
cpp
#include <fstream> #include <iostream> #include <string> int main() { std::ifstream file("missing.txt"); if (!file) { std::cerr << "File not found!" << std::endl; return 1; } // Wrong way: while (!file.eof()) can cause errors // std::string line; // while (!file.eof()) { // std::getline(file, line); // std::cout << line << std::endl; // } // Right way: std::string line; while (std::getline(file, line)) { std::cout << line << std::endl; } file.close(); return 0; }
Output
File not found!
Quick Reference
Here is a quick summary of key points for reading files in C++:
| Action | Code Example |
|---|---|
| Include file stream | #include <fstream> |
| Open file | std::ifstream file("file.txt"); |
| Check open | if (file.is_open()) { ... } |
| Read line | std::getline(file, line); |
| Close file | file.close(); |
Key Takeaways
Use
std::ifstream to open and read files in C++.Always check if the file opened successfully before reading.
Use
std::getline() in a loop to read lines safely.Avoid using
while (!file.eof()) to prevent reading errors.Close the file after finishing to free resources.