File Streams: input and output involving disk files
Key points
- With these commands, you can either input from a file or output
to a file, but not both at once.
- You must always use the include statement #include <fstream.h>
- The first step is to open the file using the command ifstream (for input) or ofstream (for output).
- When you open a file, you give it a name within the program,
called its file handle. This isn’t necessarily the same name as the name
of the file on the disk.
- Then, you can input or output using methods like those for the
console (cin >> and
cout <<), but using
the file handle in place of cin
or cout.
- If you want to input all the lines in a file, use eof to test whether you’re at the
end of the file.
- When you’re done working with a file, you should close it.
Example 1: outputting a message to a file
#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream outfile ("hello.dat"); // open stmt prepares for output to hello.dat
// outfile is the file handle
outfile << "Hello there." << endl;
outfile << "How are you?" << endl;
outfile.close(); // close file when done
return 0;
}
Example 2: inputting a single line from a
file, then outputting it to the screen
#include <iostream.h>
#include <fstream.h>
#include "apstring.h"
int main()
{
apstring text;
ifstream infile ("oneline.dat"); // open stmt prepares for input from oneline.dat
// infile is the file handle
getline(infile,text); // used getline rather than >>, to get a whole line
cout << text << endl; // now output the line to the screen
infile.close(); // close file when done
return 0;
}
Example 3: inputting many words from a
file, and output each to the screen on its own line
#include <iostream.h>
#include <fstream.h>
#include "apstring.h"
int main()
{
apstring text;
ifstream filein ("manylines.dat"); // open stmt for input from manylines.dat
// filein is the file handle
while (filein.eof() == false) // keep going as long as you're not at end of file
{
filein >> text; // input a word from the file
cout << text << endl; // now output it to the screen on its own line
}
filein.close(); // close file when done
return 0;
}