Home arrow C++ arrow Page 6 - Persistent Data: File Input and Output
C++

Persistent Data: File Input and Output


Persistence is important, particularly to programmers. Data should be persistent as well; that is, it should survive when the program is finished. This article will show you how to make your data persistent by saving it to a file. It is excerpted from chapter 13 of the book C++ Demystified, written by Jeff Kent (McGraw-Hill, 2004; ISBN: 0072253703).

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 18
August 25, 2005
TABLE OF CONTENTS:
  1. · Persistent Data: File Input and Output
  2. · First Argument—Specifying the File to Be Opened
  3. · Opening a File for Reading
  4. · Closing a File
  5. · Reading from a File
  6. · Looping Through the File
  7. · Summary

print this article
SEARCH DEVARTICLES

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 Arguments

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 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.


blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials