Reading text files is a crucial skill in C++ programming, enabling you to access and manipulate textual data stored in files. Whether you need to process log files, analyze data from external sources, or perform file-based operations, knowing how to read text files is essential. In this beginner’s guide, we will explore the fundamentals of reading text files in C++.
This C++ program reads the contents of a file named “memo.txt” and outputs each line to the console. Assumptions are that “memo.txt” can be read by the user running the program and that it is located in the same directory as the program file. The program might not function correctly if one or both of these requirements is not met.
Let’s get coding and unlock the potential of our imagination:
#include <iostream>
#include <fstream>
#include <cstring>
int main() {
std::string filename = "memo.txt";
// open file 'memo.txt' for reading
std::ifstream file{filename};
if (file.fail()) {
std::cerr << "Error: " << std::strerror(errno) << std::endl;
return 1;
}
// read each line of the file and output it to the console
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
// close file
file.close();
std::cout << "Finished reading file '" << filename << "'" << std::endl;
return 0;
}
I sincerely hope that you find this code helpful. If you wish to learn more about C++, please subscribe to our newsletter today and continue your C++ learning journey with us!