A skeleton for a program that involves file I/O
(variations are possible)
# include <fstream>
//include the header file for file I/O
# include <iostream>
using namespace std;
void main( )
{
ifstream
input_file; // “input_file” can
be replaced by any other name
ofstream
output_file; // “output_file” can be replaced
by any other name
//the following
two lines will work if the name of the file is known/given:
input_file.open
(“text1.dat”); //open input
file named text1.dat
output_file.open
(“text2.dat”); //open output file named
text2.dat
//they will change to the following lines if the name is provided by the
user:
char file_name_input[20], file_name_output[20];
cout<<”Enter the name of the input file:” ;
cin>>file_name_input;
cout<<”Enter the name of the
output file:” ;
cin>>file_name_output;
input_file.open (file_name_input);
//no double quotes
input_file.open (file_name_output); //around
the file name
if ( input_file.fail( ) ) // check for successful open
cout <<”Input file didn’t open”;
if (output_file.fail( ) )
cout<<”Output file didn’t open”;
input.file >> …….. // read information (get inputs)
output.file << …… //write information (output results)
input_file.close (
); //close files
output_file.close
( );
}