C++
  Home arrow C++ arrow Page 5 - 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 - Reading from a File


    (Page 5 of 7 )

    You input or read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream (or fstream) object instead of the cin object.

    You input or read information from a file into your program using the operator just as you use that operator to input information from the keyboard. The only difference is that you use an (or ) object instead of the object.

    The following program builds on the previous one. After writing information inputted by the user to a file named students.dat, the program reads information from the file and outputs it onto the screen:

    #include <fstream>
    #include <iostream>
    using namespace std;
    int main ()
    {
    char data[80];
    ofstream outfile;
    outfile.open("students.dat");
    cout << "Writing to the file" << endl;
    cout << "===================" << endl;
    cout << "Enter class name: ";
    cin.getline(data, 80);
    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");
    infile >> data;
    cout << data << endl;
    infile >> data;
    cout << data << endl;
    infile.close();
    return 0;
    }

    Sample input and output:

    Writing to the file
    ===================
    Enter class name: Programming
    Enter number of students: 32
    Reading from the file
    =====================
    Programming
    32

    Reading a Line of a File

    With the same program, try entering a class name with an embedded space. The following is some sample input and output:

    Writing to the file
    ===================
    Enter class name: Programming Demystified
    Enter number of students: 32
    Reading from the file
    =====================
    Programming
    Demystified

    The following are the contents of the file after the inputted data was written to it:

    Programming Demystified
    32

    The first read of the file did not read the first line of the file, “Programming Demystified.” Instead, the first read of the file only read the word “Programming” and then stopped. Consequently the second line of the program read the remainder of the first line of the file, “Demystified,” instead of the number of students.

    The ifstream object together with the stream extraction operator reads the file sequentially, starting with the first byte of the file. The first attempt to read the file starts at the beginning of the file and goes to the first whitespace character (a space, tab, or new line) or the end of the file, whichever comes first. The second attempt starts at the first printable character after that whitespace, and continues to the next whitespace character or the end of the file, whichever comes first.

    The first read attempt only read “Programming,” not “Programming Demystified,” because the read stopped at the whitespace between “Programming” and “Demystified.” The second attempt read “Demystified.” There were no further read attempts, so the number of students, 32, was never read.

    This should seem like déjà vu. We encountered a similar issue in Chapter 10 using the cin object with the stream extraction operator (>>). As in Chapter 10 with the cin object, the solution is to use getline.

    If you are working with C-strings, then you should use the getline member function. The only difference between using the getline member function here and in Chapter 10 is that here the getline member function is called by an ifstream or fstream object instead of a cin object. Accordingly, we need to replace the two calls to infile >> data with the following:

    infile.getline(data, 80);

    You also can use getline with the C++ string class. The only difference between using the getline member function here and in Chapter 10 is that here the first argument of the getline member function is an ifstream or fstream object instead of a cin object. Accordingly, we need to replace the two calls to infile >> data with the following:

    getline(infile, data);

    The following modification of the previous program uses the getline function with the C++ string class:

    #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);
    cout << data << endl;
    getline(infile, data);
    cout << data << endl;
    infile.close();
    return 0;
    }

    As the following sample input and output reflects, the first read now reads the entire first line of the file even when that line contains embedded spaces:

    Writing to the file
    ===================
    Enter class name: Programming Demystified
    Enter number of students: 32
    Reading from the file
    =====================
    Programming Demystified
    32

    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 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek