File Input and Output

File based input and output is similar to the mechanisms for keyboard and screen I/O. The main difference is that programmers must explicitly open and close files. In pseudocode, a generic program that reads input from a file might look like this.

open input file while( there is input left ) { read next input item process it} close input file

Example 2 Pseudocode to read input from a file

 

Listing 5 contains a typical way to open and read a file of integers.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: #include <fstream>#include <iostream>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { ifstream inf; inf.open("somefile.txt"); if (! inf) { // Check to see if file opened cerr << "Could not open file!" << endl; return EXIT_FAILURE; } int x; // While input remains, read an integer. while (inf >> x) { cout << x << endl; } inf.close(); // Close the input file return EXIT_SUCCESS;}
Listing 5 File input

The object used in file input is of type ifstream. Since this class is not part of the C++ language by default, we must include its library in our program. This is done in line 1. Line 9 declares an object of type ifstream, and line 10 calls the member function open to open a file. It is good programming practice to check whether an attempt to open a file actually succeeded. Also, note the use of the extraction operator in the conditional of the while-loop in line 20. As long as the extraction attempt succeeds, true is returned (and the value read from the file is assigned to x). A failure to read another integer is signaled by a value of false. This terminates the while-loop.

File output resembles file input. We still need to include a reference to the fstream library, but we use an ofstream object instead of an ifstream object. Here is an example.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: ofstream onf;onf.open("output.txt"); if (! onf) { // Check to see if file opened cerr << "Could not open file!" << endl; return EXIT_FAILURE;} for (int i = 1; i <= 10; i++) { onf << "This is line " << i << endl;} onf.close(); // Close the output file
Listing 6 File output

Keep in mind that file I/O is stream based, so it is sequential in nature. We read or write one character after another, starting at the beginning of the file and continuing until the end of the file is reached. For technical reasons, it is difficult and very costly to move back and forth, and the only access method that can be implemented reasonably efficiently is a simple beginning to end pass through the file.