Lexington High School Mathematics Math Dept. Front Page  | Student Links  | Family Links 
C++ courses Intro. Prog. I  | Intro. Prog. II  | AP Comp. Sci.  | C++ Info Page 

File Streams: input and output involving disk files

Key points

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;
}