The library fstream contains the needed information to allow for true file I/O. This file contains two classes
ifstream infile;
ofstream outfile;
The variable names could be anything that you want. After the
variable are declared, we must open the file. Opening of
the file connects the variable in your program with the actual
file on the computer. The method open() of the ifstream
and ofstream classes take one parameter which is the name of the file.
This name is given as a string. To open the file lab8a.data
for reading we would use the code:
infile.open("lab8a.data");
If we wanted the user to type in a filename and open that file, we
can follow the example shown on pp. 517 and 518. This example needs
us to create a character array which will hold the value entered by they
user and then use this array as the parameter of the open() method.
char fileName[30]; // character array to hold the filename
cout << "Enter the name of the file to read from: ";
cin >> fileName;
infile.open(fileName);
To open a file for writing, follow the same steps as was used for reading except
make sure the variable is of type ofstream instead of ifstream.
infile >> val1;
To write to the file opened with the variable outfile, we could
use the code:
outfile << "The result is: " << val << endl;
infile.close();
outfile.close();
infile.open ("lab8a.data");
if (infile.fail() == true)
{
cout << "Opening file lab8a.data for input failed. Goodbye" << endl;
exit(1);
}
The above code will quit the program after printing an error message
if the file failed to open.
When reading input from a file, we often read until the end of the file is reached. This can be checked by using the eof() method. This method takes no parameters and returns a true value if the file has had everything read from it. See page 513. This use of this method can be shown in the following code which will copy a file:
ifstream infile;
ofstream outfile;
char ch;
infile.open("original.txt");
outfile.open("copy.txt);
// check for successful opening is omitted
infile.get(ch)
while (infile.eof() == false)
{
outfile << ch;
infile.get(ch);
}
// closing of files is omitted
You may turn in the assignment to your TA during lab or place it in his mailbox in 905 SEO. It is suggested that you place it in his mailbox just in case you are unable to attend lab. You are to hand in a print out of your program to do the following to your TA.
Hand in a print out of your program to your TA.