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).
Persistent Data: File Input and Output (Page 1 of 7 )
As a kid, I had to listen patiently, or not so patiently, to endless (so it seemed at the time) lectures from my parents on how I could be better, or do better. After I became an adult, I realized to my amazement that my parents more often than not were right. Indeed, after I became a parent, I realized to my horror that I was repeating their lectures to my own children, who, of course, today enjoy these “talks” about as much I used to.
One of my parents’ favorite lectures was about how important it is to be persistent. Once again, mom and dad showed true insight, because, though persistence is a very valuable trait in any person, it is particularly important in programmers.
Data, as well as programmers, should be persistent. By persistent, I mean the data should survive when the program is finished. Can you imagine if, after typing this chapter, when I exited Microsoft Word, everything I typed was lost?
With the programs we have written so far, this is exactly what would happen. Whatever values we have stored in variables do not persist, or survive, when the program is finished. Instead, the data is lost because the data is stored in RAM (random access memory), which is cleared when the program (or the computer) stops running.
Fortunately, Microsoft Word (and most programs for that matter) has the capability to save data to a file on the computer’s hard drive or other storage medium so that data later can be retrieved when needed. That data persists after the termination of the program or even after the computer is turned off.
This chapter will show you how to make your data persistent by saving it to a file. Of course, saving the data accomplishes little unless you can later retrieve it, so this chapter also will show you how to retrieve data from a file.
Text vs. Binary Files
If you work on a computer, you work with files. You may have worked with hundreds if not thousands of files. However, have you ever stopped to think about what a file exactly is?
A file is a collection of data, and is located on persistent storage (discussed in Chapter 2) such as a hard drive, a CD-ROM, or other storage device.
A file is referred to by a name (called, naturally enough, a filename), which often is descriptive of the nature or contents of the file. For example, the Microsoft Word document for this chapter may be named chapter13.
A filename usually has an extension, beginning with a period (.). For example, if the file for this chapter is named chapter13.doc, the extension is .doc.
The purpose of the file extension is to indicate the type of date in the file and the program that normally is used to access the file. Accordingly, by convention, .doc is the extension for files normally accessed by Microsoft Word, .xls is the extension for files normally accessed by Microsoft Excel, and so forth. One extension you may have used frequently when working with this book is .cpp, for C++ source files.
As there are many types of programs, there are many types of files, and many different file extensions. However, fundamentally, there are two types of files: text and binary.
A text file is, as the name suggests, a file that contains text. An example is a file you might create in Notepad or another plain-text editor.
The meaning of binary in a binary file is less intuitive. View a Microsoft Word document in Notepad or another plain-text editor, such as the one I used to type this chapter. You will see, in addition to the text, strange characters such as ã6, ÌL, h5, and dark vertical lines that most definitely do not appear in the text. These are formatting codes used by Microsoft Word to format the text, such as for tables, bulleted and numbered lists, and so forth.
Text files can only store text. By contrast, binary files can store other types of information, such as images, database records, executable programs, and so forth. Consequently, more complex programs, such as Microsoft Word, Excel, or Access, store data in binary files.
Text files are somewhat simpler than binary files to access, read, and write. Consequently, file access usually is introduced using text files, with binary files a more advanced topic. This being an introductory-level book, I will use text files when explaining file access. However, when pertinent during this chapter, I also will refer to binary files.
The fstream Standard Library
We have been using the iostream standard library, which supports, among other functionalities, cin for reading from standard input (usually the keyboard), and cout for outputting to standard output (usually the monitor).
We have been using the standard library, which supports, among other functionalities, for reading from standard input (usually the keyboard), and for outputting to standard output (usually the monitor).
Reading or writing from a file requires another standard library, fstream. The fstream standard library is included with the statement:
Both iostream and fstream have in common the word “stream.” This is no accident. Both standard libraries concern streams of bytes. The iostream library concerns streams of bytes resulting from the “io” in iostream, input and output. The fstream standard library concerns streams of bytes resulting from the “f” in fstream, a file.
The fstream header file defines three new data types:
ofstream This data type represents the output file stream—the “o” in ofstream standing for output. The direction of output is from your program out to a file. The ofstream data type is used to create files and to write information to files. It cannot be used to read files.
ifstream This data type represents the input file stream—the “i” in ifstream standing for input. The direction of input is from a file into your program.
The ifstream data type is used to read information from files. It cannot be used to create files or to write information to them.
fstream This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream. It can create files, write information to files, and read information from files.
The File Access Life Cycle
When your program accesses a file, whether to read it, write to it, or both, it goes through the following steps.
The file first must be opened. This establishes a path of communication between the file and a stream object in your program—fstream,ofstream, or ifstream—used to access the file.
Your program then reads from, or writes to, the file (or both). This section will discuss writing to a file before reading to it, but in your program the order could be reversed. Additionally, your program may only read from a file, or only write to a file.
Finally, your program closes the file. Maintaining the path of communication between the file and the stream object in your program requires system resources, so closing the file frees those resources when they are no longer needed. Additionally, you may not be able to access the file later in your program if you did not close it after the previous access.
Opening a File
A file must be opened before you can read from it or write to it. As discussed in the introduction to this section, opening a file establishes a path of communication between the file and a stream object in your program. Opening a file for writing is first discussed.
Opening a File for Writing
Either the ofstream or fstream object may be used to open a file for writing. However, the ifstream object cannot be used for this purpose because it only may be used to read from a file.
Either the or object may be used to open a file for writing. However, the object cannot be used for this purpose because it only may be used to read from a file.
Both the ofstream and fstream objects may open a file one of two ways. The first way is using a member function named, as you might expect, open. The second alternative is using a constructor, which is explained in the “The fstream or ofstream Constructor” section later in this chapter.
The Open Member Function
Both the ofstream and fstream objects use an open member function, whose first argument is the name and location of the file to be opened. However, whether you include a second argument may depend on whether the ofstream or fstream object is calling the open member function, or whether you want to access the file in a different “mode” than the default.
Both the and objects use an member function, whose first argument is the name and location of the file to be opened. However, whether you include a second argument may depend on whether the or object is calling the member function, or whether you want to access the file in a different “mode” than the default.