Persistent Data: File Input and Output - Looping Through the File
(Page 6 of 7 )
In the previous program, exactly two read attempts were made because we knew there were two lines of data in the file, no more, no less. However, often we may not know the number of pieces of data to be read. All we want is to read the file until we have reached the end of it.
The ifstream object has an eof function, eof being an abbreviation for end of file. This function, which takes no arguments, returns true if the end of the file has been reached, and false if otherwise.
However, the eof function is not as reliable with text files as it is with binary files in detecting the end of the file. The eof function’s return value may not accurately reflect if the end of the file was reached if the last item in the file is followed by one or more whitespace characters. This is not an issue with binary files since they do not contain whitespace characters.
A better choice is the fail member function, discussed in the earlier section “Checking if the File Was Opened.” The following code fragment shows how to use the fail member function in reading a file until the end of the file is reached:
ifstream infile;
infile.open("students.dat");
infile >> data;
while(!infile.fail())
{
infile >> data;
cout << data;
}
infile.close();
The preceding code fragment has two infile >> data statements, one before the loop begins, the other inside the loop. The reason is that the end of file is not detected until after a read attempt is made. Thus, if the infile >> data statement before the loop was omitted and the file was empty, the cout << data statement would execute before an attempt was made to detect if the end of file had been reached.
NOTE: A do while loop could be used instead of a while loop. This would dispense with the need to check for end of file before entering the loop, but add the requirement to check inside the loop if (using an if statement) end of file had been reached. This is the usual tradeoff between while and do while loops.
NOTE: A do while loop could be used instead of a while loop. This would dispense with the need to check for end of file before entering the loop, but add the requirement to check inside the loop if (using an if statement) end of file had been reached. This is the usual tradeoff between while and do while loops.
Modifying the previous program, the code now would read
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string data;
ofstream outfile;
outfile.open("students.dat");
cout << "Writing to the file" << endl;
cout << "===================" << endl;
cout << "Enter class name: ";
getline(cin, data);
outfile << data<< endl;
cout << "Enter number of students: ";
cin >> data;
cin.ignore();
outfile << data<< endl;
outfile.close();
ifstream infile;
cout << "Reading from the file" << endl;
cout << "=====================" << endl;
infile.open("students.dat");
getline(infile, data);
while(!infile.fail())
{
cout << data << endl;
getline(infile, data);
}
infile.close();
return 0;
}
File Stream Objects as Function ArgumentsChapter 9 explained how you can use functions to make your code more modular. In that spirit, let’s rewrite the previous program to add two functions, each to be called from main: writeFile to open a file for writing using an ofstream object, and readFile to open a file for reading using an ifstream object. Each function includes code to check if the file was opened successfully and returns a Boolean value indicating whether the file was opened successfully:
Chapter 9 explained how you can use functions to make your code more modular. In that spirit, let’s rewrite the previous program to add two functions, each to be called from to open a file for writing using an object, and to open a file for reading using an object. Each function includes code to check if the file was opened successfully and returns a Boolean value indicating whether the file was opened successfully:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
bool writeFile (ofstream&, char*);
bool readFile (ifstream&, char*);
int main ()
{
string data;
bool status;
ofstream outfile;
status = writeFile(outfile, "students.dat");
if (!status)
{
cout << "File could not be opened for writingn";
cout << "Program terminatingn";
return 0;
}
else
{
cout << "Writing to the file" << endl;
cout << "===================" << endl;
cout << "Enter class name: ";
getline(cin, data);
outfile << data<< endl;
cout << "Enter number of students: ";
cin >> data;
cin.ignore();
outfile << data<< endl;
outfile.close();
}
ifstream infile;
status = readFile(infile, "students.dat");
if (!status)
{
cout << "File could not be opened for readingn";
cout << "Program terminatingn";
return 0;
}
else
{
cout << "Reading from the file" << endl;
cout << "=====================" << endl;
getline(infile, data);
while(!infile.fail())
{
cout << data << endl;
getline(infile, data);
}
infile.close();
}
return 0;
}
bool writeFile (ofstream& file, char* strFile)
{
file.open(strFile);
if (file.fail())
return false;
else
return true;
}
bool readFile (ifstream& ifile, char* strFile)
{
ifile.open(strFile);
if (ifile.fail())
return false;
else
return true;
}
For each function, the file stream object is passed by reference instead of by value even though neither function changes the contents of the file. The reason is that the internal state of a file stream object may change with an open operation even if the contents of the file may not change.
Next: Summary >>
More C++ Articles
More By McGraw-Hill/Osborne
|
This article is excerpted from chapter 13 of the book C++ DeMYSTifieD, written by Jeff Kent (McGraw-Hill, 2004; ISBN: 0072253703). Check it out at your favorite bookstore. Buy this book now.
|
|