File Names as Input
In file I/O, sometimes we want to input the name of a file from the keyboard. This can be done using a string since a file name is a string.
-
A string is just a sequence of characters
-
We need to declare a variable to hold a string. This can be done by the declaration:
char filename[16];
which can hold a string that contains 15 or fewer characters.
-
This type of strings (turns out to be an array of characters) is known as a cstring. The null character '\0' is used to mark the end of the cstring.
-
Strings will be dealt with in ch. 10.
-
An example is shown as follows:
//Reads three numbers from the file specified by the user, sums the
//numbers, and writes the sum to another file specified by the user.
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main( )
{
int first, second, third;
// declare 2 character arrays for the input and output file names
char in_file_name[16], out_file_name[16];
ifstream in_stream;
ofstream out_stream;
cout << "I will sum three numbers taken from an input\n"
<< "file and write the sum to an output file.\n";
cout << "Enter the input file name (maximum of 15 characters):\n";
cin >> in_file_name;
cout << "Enter the output file name (maximum of 15 characters):\n";
cin >> out_file_name;
cout << "I will read numbers from the file "
<< in_file_name << " and\n"
<< "place the sum in the file "
<< out_file_name << endl;
in_stream.open(in_file_name);
if (in_stream.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
out_stream.open(out_file_name);
if (out_stream.fail( ))
{
cout << "Output file opening failed.\n";
in_stream.close( );
// otherwise you exit the program without closing
// the input file!
exit(1);
}
in_stream >> first >> second >> third;
out_stream << "The sum of the first 3\n"
<< "numbers in " << in_file_name << endl
<< "is " << (first + second + third)
<< endl;
in_stream.close( );
out_stream.close( );
cout << "End of Program.\n";
return 0;
} //end main