CHAPTER 10 File Input and Output Objectives

CHAPTER 10 File Input and Output Objectives • • • • • • • • • • • • • • • 366 To use ofstream for output (§10.2.2) and ifstream for input (§10.2.2)....
Author: Peter Foster
2 downloads 0 Views 134KB Size
CHAPTER 10 File Input and Output Objectives • • • • • • • • • • • • • • •

366

To use ofstream for output (§10.2.2) and ifstream for input (§10.2.2). To test whether a file exists (§10.2.3). To test the end of a file (§10.2.4). To write data in desired format (§10.3). To read and write data using the getline, get, and put functions (§10.4). To use an fstream object to read and write data (§10.5). To open a file with specified modes (§10.5). To use the eof(), fail(), bad(), and good() functions to test stream states (§10.6). To understand the difference between text I/O and binary I/O (§10.7). To write binary data using the write function (§10.7.1). To read binary data using the read function (§10.7.2). To cast primitive type values and objects to character arrays using the reinterpret_cast operator (§10.7). To read/write objects (§10.7.4). To use the seekp and seekg functions to move the file pointers for random file access (§10.8). To open a file for both input and output to update files (§10.9).

10.1 Introduction Data stored in variables, arrays, and objects are temporary; they are lost when the program terminates. To permanently store the data created in a program, you need to save them in a file on a disk or a CD. The file can be transported and can be read later by other programs. C++ defines the ifstream, ofstream, and fstream for processing and manipulating files. These classes are all defined in the header file. The ifstream class is for reading data from a file, the ofstream class is for writing data to a file, and the fstream class can be used for updating data in a file.

10.2 Simple Text I/O This section demonstrates how to perform simple input and output. Let us first consider output. 10.2.1 Writing Data to a File The ofstream class can be used to write primitive data type values, arrays, strings, and objects to a text file. Listing 10.1 demonstrates how to write data. The program creates an instance of ofstream and writes two lines to the file “scores.txt”. Each line consists of first name (a string), middle name initial (a character), last name (a string), and score (an integer). Listing 10.1 WriteData.cpp (Text File Output)

***PD: Please add

#include #include using namespace std; int main() { ofstream output; scores.txt // Create a file output.open("scores.txt"); // Write two lines output