"Reprint" of C + + files and streams

Source: Internet
Author: User
Tags terminates

http://www.iteedu.com/plang/ccpp/cppdxjch2b/111.php

The C + + language sees each file as an ordered stream of bytes (see Figure 14. 2), each file either ends with a file terminator (End-of-file marker) or ends at a specific byte number (the specific byte number of the ending file is recorded in the data structure maintained and managed by the system). When you open a file, the file is associated with a stream. In the 11th chapter, the 4 objects of CIN, cout, Cerr and clog are automatically generated. A communication channel between a stream provider and a specific file or device associated with these objects. For example The CIN object (standard input Stream object) enables the program to input data from the keyboard, cout objects (standard output stream objects) to enable the program to output data to the screen, Cerr and clog objects (standard error stream objects) to enable the program to output error messages to the screen.

Figure 14. 2 C + + sees a file as n bytes

To do file processing in C + +, include header file <iostream.h> and <fstream.h>. <fstream.h> header files include the Stream class Ifstream (from file input), ofstream (to file output), and fstream (from file input, output) definitions. The objects that generate these stream classes can open the file. These stream classes derive from the IStream, Ostream, and iostream classes, respectively, that inherit their functionality. In this way, the member functions, operators, and flow manipulation operators described in the 11th chapter "C + + input, output stream" are also available for file flow. The inheritance relationship of the I/O class is shown in Figure 14.3.

14. 4 Establishing sequential Access files

Because C + + looks at files as unstructured byte streams, records and so on are not present in C + + files. To do this, programmers must provide a file structure that meets the requirements of a particular application. The following example shows how a programmer imposes a record structure on a file. List the programs first, and then analyze the details.

The program in Figure 14.4 establishes a simple sequential access file that can be used to track the amount owed by the company's borrowing customers in the Accounts receivable management system. The program is able to obtain each customer's account number, customer name and settlement amount to the customer. A customer's data constitutes the customer's record. The account is used as the record key in the application, and the file is established and maintained in the order of account. The example program assumes that the user is logged by key in the order of the account (in order to allow the user to type records in any order, the perfect Receivables Management system should have the ability to sort). Then save the typed record and write to the file.

//Fig. 14.4; fig14_04.cpp//Create a sequential file #include <iostream.h> #include <fstream. h> #include <stdlib.h> int main () {//Ofstream constructor opens file Ofstream outclientfile ("Clients.dat",   Ios::out);     if (!outclientfile) {//overloaded! Operator Cerr << "File could not being opened" << Endl;   Exit (1); Prototype in Stdlib.h} cout << "Enter the account, name, and balance.\n" << "Enter End-of-file To end input.\n?   ";   int account;   Char name[30];   float balance; while (CIN >> account >> name >> balance) {outclientfile << account << ' << na     Me << ' << balance << ' \ n ';   cout << "?";  } return 0; Ofstream destructor closes file} 

Figure 14. 4 Creating sequential files

Now let's study the program. As mentioned earlier, files are opened by creating objects of the Ifstream, Ofstream, or fstream stream classes. Figure 14. 4, to open the file for output, the Ofstream object is generated. Pass in two parameters to the object constructor--file name and file open mode. For Ostream objects, the file can be opened either ios::out (outputting data to a file) or Ios::app (adding data to the end of the file without modifying the existing data in the file). Existing files are truncated when opened with Ios::out, that is, all data in the file is deleted. If the specified file does not already exist, the file is generated with the file name. The following statement (line 10th):

Ofstream outclientfile ("Clients.dat"). Ios::out);

Generates a Ofstream object Outclientfile associated with the file Clients.dat that opened the output. The arguments "Clients.dat" and Ios::out pass into the Ofstream constructor, which opens the file, thereby establishing a communication line with the file. By default, the Ofstream object is opened for output, so the following statement:

Ofstream outclientfile ("Clients.dat");

You can also open clients.dat for output. Figure 14.5 lists how the file is opened.

Common Programming Error 14.1

Open an existing file that the user wants to keep the data for output (ios::out mode). This action deletes the contents of the file without warning.

Common programming Error 14. 2

Indicates a file with the wrong Ofstream object.

You can also generate a Ofstream object without opening a specific file, and you can then connect the file to the object later. For example, the following declaration:

Ofstream Outclientfile;

Generates a Ofstram object outclientfile. The Ofstream member function open opens the file and connects it to an existing Ofstream object, as follows:

Outclientfile Open ("Clients.dat", ios::out);

------------------------------------------------------------------------------------------  how            to open a file Description------------------------------------------------------------------------------------------  Ios::app              Writes all output to the end  of the file ios::ate              open the file for output, the well moves to the end of the file (typically used to add data) data can be written                            anywhere in the file  ios::in               Open the file for input  Ios::o UT              open file for output  ios::trunc            Delete the existing contents of the file (is the default action of Ios::out)  ios::nocreate         If the file does not exist, the file open fails  Ios::noreplace        If the file exists, The file fails to open------------------------------------------------------------------------------------------

Figure 14. 5 How to open files

Common programming Error 14. 3

Forget to open the file before referencing it.

When the Ofstream object is generated and ready to open, the program tests whether the open operation was successful. Operations in the following if structure (lines 12th through 15th):

   if (!outclientfile) {        cerr << "File could not be opened" << Endl;        Exit (1);    }

Use the overloaded iOS operator member function operator! to determine whether the open operation was successful. If the open operation's stream is set failbit or badbit, this condition returns a value other than 0 (true). A possible error is an attempt to open a file that does not exist, tries to open a file that reads no permissions, or tries to open a file to write a person while there is insufficient disk space.

If the condition indicates that the open operation is unsuccessful. The output error message "File could not is opened", and call the function exit to end the program, the exit parameter is returned to the environment in which the program was called, and parameter 0 indicates that the program terminated normally. Any other value indicates that the program terminated because of an error. The value returned by exit allows the calling environment (usually the operating system) to respond appropriately to the error.

Another overloaded iOS operator member function, operator void*, turns the stream into a pointer that tests to 0 (a null pointer) or not 0 (any other pointer value). Returns 0 (false) if the Failbit or Badbit (see Chapter 11th) Convection is set. The conditions for the following while header automatically call the operator void* member function:

while (CIN >> account >> name >> balance)

The condition remains true as long as the failbit and badbit of CIN are not set. The input file terminator sets the failbit of CIN. The operator void* function can test the file terminator of an input object without having to explicitly call the EOF member function on the input object.

If the file opens successfully, the program starts processing the data. The following statements (lines 17th and 18th) prompt the user to enter a different domain for each record, or enter a file terminator when the data entry is complete:

cout << "Enter the account, name, and balance." << "Enter EOF to and input.";

Figure 14. 6 lists the keyboard combinations for file terminators in different computer systems.

---------------------------------------------------    Computer Systems                   Key combination---------------------------------------------------    Unix system                   D    IBM pc and its compatible machine           Z    Macintosh                  D    VAX (VMS)                   z---------------------------------------------------

Figure 14. 6 file End key combinations in various popular computer systems

The following statement (line 24th):

while (CIN >> account >> name >> balance)

Enter each set of data and determine whether to lose the file terminator. When entering a file terminator or illegal data, the stream read operator of Cin >> returns 0 (usually this stream read operator >> return CIN), while the structure terminates. The user enters the file terminator to tell the program that there is no more data to process. Sets the file terminator when the user enters a file terminator key combination. The while structure loops as long as no input file terminator is entered.

Lines 25th and 26th:

Outclientfile << account << ' << name<< ' << balance << ';

Writes a set of data to the file "Clients.dat" with the Outclientfile object associated with the file at the beginning of the flow-plug operator <<.

This data can be obtained using a program that reads the file (see 14. Section 5). Note the file generated in Figure 14.4 is a text file that can be read with any text editor.

After the loser file Terminator, main terminates, causing the Outclientfile object to be deleted, thus calling its destructor, closing the file

Clients.dat. The programmer can explicitly close the Ofstream object with the member function close as follows:

Outclientfile.close ();

Performance Tip 14. 1

Files that are no longer referenced by the program should be explicitly closed immediately. This reduces the resources that are consumed when the program continues to execute. This method can also improve the clarity of the program.

In Figure 14. 4 of the execution examples, the user loses five records. Then type the end of the file that represents the end of the data entry (^z on the screen of the IBM PC compatibility machine). The output dialog window does not describe how these records are organized in a file. In order to verify that the file was established successfully, the following section describes the program that reads and prints the file.

"Reprint" of C + + files and streams

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.