Home arrow C++ arrow Page 2 - 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 - First ArgumentóSpecifying the File to Be Opened
(Page 2 of 7 )

The file to be opened for writing need not already exist. If it does not, attempting to open it for writing to it automatically will create it with the specified name at the specified location. However, whether or not the file yet exists, you need to specify a file name and location.

Accordingly, whether the ofstream or fstream object is calling the function, the first argument specifies the name and location of the file to be opened. This information may be provided by using either the relative path or absolute path of the file. The terms relative path and absolute path are new, so letís discuss them now.

The relative path is the path relative to the location of your program. For example, the following statements open for writing a file, students.dat, that is in the same directory as the program:

ofstream outfile;
outfile.open("students.dat");

By contrast, the absolute path is the path starting with the drive letter, and including each directory and subdirectory until the file is reached. For example, if the students.dat file is in the Classes subdirectory of the College directory of my C drive, it would be opened for writing, using the absolute path, as follows:

ofstream outfile;
outfile.open("c:collegeclassesstudents.dat");


NOTE:
Two backslashes are necessary because one backslash is used to note an escape sequence. Two backslashes is the escape sequence for one backslash.

 

Whether you use a relative or absolute path, the argument for the open function need not be a string literal. It also may be a string variable, as in the following code fragment:

ofstream outfile;
char filename[80];
cout << "Enter name of file: ";
cin >> filename;
outfile.open(filename);


NOTE: As a general rule, using a relative path is preferable, particularly if the program will be used on different machines. While the location of the data file relative to the program directory may remain the same, there is no guarantee that the particular placement of the program on one computerís directory structure will be the same as anotherís.

NOTE: As a general rule, using a relative path is preferable, particularly if the program will be used on different machines. While the location of the data file relative to the program directory may remain the same, there is no guarantee that the particular placement of the program on one computerís directory structure will be the same as anotherís.

Second ArgumentóFile Mode

The second argument of the open member function defines the mode in which the file should be opened. One choice is whether the file should be opened for writing, reading, or both. However, there are other choices, each called a file mode flag. Table 13-1 lists the file mode flags:

 

File Mode Flag

Description

ios::app

Append mode. The fileís existing contents are preserved and all output is written to the end of the file.

ios::ate

If the file already exists, the program goes directly to the end of it. Output may be written anywhere in the file. This flag usually is used with binary mode.

ios::binary

Binary mode. Information is written to the file in binary format, rather than in the default text format.

ios::in

Input mode. Information will be read from the file. The file will not be created if it does not exist.

ios::out

Output mode. Information will be written to the file. By default, the existing file contents will be overwritten.

ios::trunc

If the file already exists, its contents will be truncated, another word for deleted or overwritten. This is the default mode of ios::out.

Table 13-1 File Mode Flags

If you use the ofstream object to open a file, you do not need any file mode flags. Indeed, the examples in the previous section did not use any file mode flags. An ofstream object may only be used to open a file for writing, and cannot be used to open a file for reading. Therefore, there is no need to specify the ios::out flag; use of that flag is implied by use of the ofstream object to open the file.

However, you may want to use one or more file mode flags with the open member function of the ofstream object if you do not want the default, which is to open the file in text rather than binary mode and overwrite rather than append to the existing file contents. One example of when you might want to append is an error log file, which keeps track of errors that may occur in a program. When a new error occurs, you donít want to erase the history of prior errors, but rather you want to add to that history.

You can combine two or more flags when opening a file. For example, the following statements open a file in binary mode and to append rather than to overwrite. The two file mode flags are combined using the bitwise or operator (|):

ofstream outfile;
outfile.open("students.dat", ios::binary | ios::app);


NOTE: The bitwise or operator | is not the same as the logical or operator || even though they share the name or and the keystroke |.

NOTE: The bitwise or operator is not the same as the logical or operator even though they share the name or and the keystroke

While you donít need to specify any file mode flags if you use the ofstream object to open a file, you should specify file mode flags if you use the fstream object to open a file. Whereas an ofstream object may only be used to open a file for writing and not reading, an fstream object may be used for both purposes. Therefore, you should specify whether you are using the open member function of the fstream object to open the file for writing, reading, or both.

The following code fragment uses the open member function of the fstream object to open the file for writing only:

fstream afile;
afile.open("students.dat", ios::out);

The fstream or ofstream Constructor

You also may use the fstream or ofstream constructor to open a file for writing. A constructor is a function that is automatically called when you attempt to create an instance of an object.

You also may use the or constructor to open a file for writing. A is a function that is automatically called when you attempt to create an of an object.

An object instance is akin to a variable of a primitive data type, such as an int. For example, the following statement could be characterized as creating an instance, named age, of an integer:

int age;

Similarly, the following statement creates an fstream instance named afile:

fstream afile;

Object constructors may be overloaded, such that for the same object there may be a constructor with no arguments, a constructor with one argument, a constructor with two arguments, and so forth. For example, the previous statement, fstream afile, is called the no-argument constructor of the fstream object.

The following statement calls the one-argument constructor of the ofstream object, both creating an ofstream instance and opening the file students.dat for output:

ofstream outFile(ďstudents.dat", ios:out);

The following statement calls the two-argument constructor of the fstream object, both creating an fstream instance and opening the file students.dat for output:

fstream aFile(ďstudents.dat", ios:out);

In essence, declaring an ofstream (or fstream) variable in one statement and then calling the open member function in a second statement is analogous to declaring a primitive variable in one statement and then assigning it a value in a second statement, such as:

int age;
age = 39;

By contrast, using the one or two argument ofstream (or fstream) constructor is analogous to initializing a primitive variable, such as:

int age = 39;

One alternative is not inherently better than the other. Usually, the specific needs of a particular program will dictate which alternative better fits your needs.


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