C++
  Home arrow C++ arrow Page 6 - Persistent Data: File Input and Output
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Persistent Data: File Input and Output
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 8
    2005-08-25

    Table of Contents:
  • Persistent Data: File Input and Output
  • First Argument—Specifying the File to Be Opened
  • Opening a File for Reading
  • Closing a File
  • Reading from a File
  • Looping Through the File
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More C++ Articles
    More By McGraw-Hill/Osborne


       · I can create the persistent file and write to it and read from it, but I want to...
     

    Buy this book now. 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.

    C++ ARTICLES

    - 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++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 10 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek