C++ Notes: Reading Text Files
Reading a text file is very easy using
an ifstream (input file stream).
- Include the necessary headers.
#include <fstream>
using namespace std;
- Declare an input file stream (
ifstream) variable. For example,
ifstream myInput;
- Open the file stream. For example,
myInput.open("C:\\temp\\datafile.txt");
Path names in MS Windows use backslashes (\). Because the backslash is
also the string escape character, it must be doubled. If the full path
is not given, most systems will look in the directory that contains the
object program.
- Check that the file was opened. For example, the open
fails if the file doesn't exist, or if it can't be read because
another program is writing it. A failure can be detected with
code like that below using the ! (logical not) operator:
if (!myInput) {
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
- Read from the stream in
the same way as
cin. For example,
while (myInput >> x) {
sum = sum + x;
}
- Close the input stream. Closing is essential for output streams
to be sure all information has been written to the disk, but
is also good practice for input streams to release
system resources and make the file available for other
programs that might need to write it.
myInput.close();
Example
The following program reads ints from a file and prints their sum.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream myInput;
int x;
int sum = 0;
myInput.open("test.txt");
if (!myInput) {
cerr << "Unable to open test.txt.";
exit(1);
}
while (myInput >> x) {
sum += x;
}
cout << "total = " << sum << endl;
myInput.close();
return 0;
}