Section 11.5 File Input
In C++ we include the
<fstream>
library to work with files. It provides two key types of object: ifstream
(input file stream) and ofstream
(output file stream). These objects are used to read from and write to files respectively.
To read from a file, we need to create a
std::ifstream
object. (If you are using namespace std;
you can shorten that to ifstream
). Like making a string or any other variable, we need to give the stream a name:
ifstream inFile;
Once we have a stream object, we need to open a file. This is done with the
open
method of the stream object. The open
method takes a string as a parameter that is the name of the file we want to open. Once the file is open, we can read from it using the >>
operator just like we were reading from the console.
This program opens the datafile
Numbers.txt
shown on the previous page and reads the first two numbers from it:
The streams provided by
<fstream>
are a bit frustrating in that they do not automatically report errors. If you want to know if the stream is OK, you have to use one of these checks:
// Check if the stream is OK
if (inFile.good()) {
// stream is OK
}
// Or short version:
if (inFile) {
// stream is OK
}
// Check for errors
if (inFile.error()) {
// stream is NOT OK
}
// Or short version:
if (!inFile) {
// stream is NOT OK
}
Here is a version of the program that checks to make sure the file was opened successfully. It also uses a shortened form of creating the
ifstream
and opening a file with it.
Try changing the filename this program is opening to see that it catches the issue. By returning from main, we end the program early when there was a failure opening the file. (Returning a non-zero value is the convention for βthere was an error in the programβ). We could instead throw an exception, try opening a different file, etc...
Checkpoint 11.5.2.
Checkpoint 11.5.3.
Checkpoint 11.5.4.
The code below reads data from a file called
input.txt
. What is wrong with the following code?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string filename = "input.txt";
ifstream infile;
infile.open(filename);
string input;
filename >> input;
}
- Since we are dealing with an input file, we should use
ifstream
. - The values used with
>>
are incorrect. - We are supposed to read input through the
ifstream
object, not the filename. This line should beinfile >> input;
. - We cannot use a variable to store the filename.
- Since the name of the file is just a string, we can store it in a variable.
- There are no errors with this code.
- Take another look at the code. Are we reading the input correctly into
input
?
You have attempted of activities on this page.