Checkpoint 11.5.1.
What happens if you try changing the filename to something else like
"oops.txt"?
- An error message is printed and you are asked for a new file name
- All of the numbers show up as 0
- There is an exception
<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.
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;
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.
Numbers.txt shown on the previous page and reads the first two numbers from it:
"oops.txt"?
<fstream> are a bit frustrating in that they do not automatically report errors. When something bad happens (like trying to open a file that does not exist), the stream simply goes into a failure state and refuses to do anything more. In the case of the program above, it never even tries to read in values when we do inFile >> input;. The variable just keeps its existing value.
// 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.fail()) {
// stream is NOT OK
}
// Or short version:
if (!inFile) {
// stream is NOT OK
}
ifstream and opening a file with it.
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;
}
ofstream instead of ifstream.ifstream.>> are incorrect.ifstream object, not the filename. This line should be infile >> input;.