C + + Learning 47 File concept file stream class and file stream object file open and close

Source: Internet
Author: User

So far, the input and output we have discussed is the object of the system-specified standard device (the input device is the keyboard and the output device is the monitor). In real-world applications, disk files are often used as objects. The data is read from the disk file and the data is output to the disk file. Disk is the external memory of the computer, it can retain information for a long time, can read and write, can be refreshed and rewritten, easy to carry, so it is widely used.

Document (file) is an important concept in program design. The so-called "file", generally refers to the collection of data stored on the external media. A batch of data is stored as files on external media (such as disks, CDs, and USB drives). The operating system manages the data in files, that is, if you want to find data on external media, you must first locate the file you specified by file name, and then read the data from that file. To store data on external media, you must also create a file (identified by the file name) before you can output data to it.

External memory files include disk files, CD-ROM files, and USB drive files. The most widely used is the disk file, for the narrative convenience, the tutorial where the use of external memory files are represented by a disk file, in the program of the CD-ROM files and the use of the USB drive file is the same as the disk file.

For users, there are two main types of files that are commonly used, such as program files, such as source program Files (. cpp) for C + +, target files (. obj), executables (. exe), and so on. One is the data file, when the program runs, it is often necessary to output some data (the final result of the run or intermediate data) to the disk to be stored, and then to enter the computer memory from the disk later. This disk file is the data file. The input and output objects in the program are data files.

Depending on the organization of the data in the file, it can be divided into ASCII files and binaries. An ASCII file is also called a text file or a character file, and each byte of it is placed in an ASCII code that represents a character. A binary file, also known as an internal format file or a byte file, is the output of in-memory data to disk as it is stored in memory.

For character information, it is stored in ASCII code in memory, so the data form is the same regardless of whether the output is in ASCII file or binary file. But for numeric data, the two are different. For example, there is a long integer 100000, which accounts for 4 bytes in memory, and if it is output in the internal format, it occupies 4 bytes in the disk file, and if it is converted to ASCII format output, it will account for 6 bytes.

Data that is output in ASCII format corresponds to character one by one, and a byte represents a character that can be displayed or printed directly on the screen. This method is easy to use, more intuitive, easy to read, easy to input and output characters. However, it typically takes up more storage space and costs the conversion time (the conversion between binary forms and ASCII code). Using the internal format (binary form) to output values, you can save external memory space, and do not need to convert time, but one byte does not correspond to a character, can not directly display the contents of the file. If some intermediate result data is temporarily saved in the disk file while the program is running, and then it needs to be entered into the memory, it is most appropriate to save it with a binary file. If this is to be displayed and printed for reading, it should be output in ASCII format. The ASCII file is now available, and its contents can be viewed directly on the display.

C + + provides low-level I/O functionality and advanced I/O functionality. Advanced I/O functionality is to combine several bytes into a meaningful unit (such as integers, single-precision numbers, double-precision numbers, strings, or user-defined types of data) and then enter and output as ASCII characters. For example, sending data from memory to the display output is an advanced I/O feature that converts in-memory data to ASCII characters, and then outputs them as integers, single-precision numbers, and double-precision numbers, respectively. This type-oriented input and output is widely used in programs and is convenient for users. However, in the transfer of large-capacity files due to the data format conversion, slower, inefficient.

The so-called low-level I/O function is input and output in bytes, and the data format is not converted at input and output. This input and output is in binary form. Typically used to transfer a batch of bytes between memory and device. This input and output speed, high efficiency, general large-capacity file transfer with unformatted conversion of I/O. However, it is not easy to use.

A file stream is a stream of data that is an input and output object as an external memory file. The output file stream is the data that flows from memory to the external memory file, and the input file stream is the data that flows from the external memory file to memory. Each file stream has a memory buffer corresponding to it.

Differentiate between file stream and file concepts without mistaking the flow of files as a stream of several files. The file stream itself is not a file, but a stream of input and output objects as a file. To input output to a disk file, you must do so through a file stream.

Several file classes are defined in the C + + I/O class library, specifically for input and output operations on disk files. In Figure 13.2 (see more: Classes and objects related to C + + input and output), there are 3 file classes for file operations in addition to the standard input and output stream classes IStream, Ostream, and iostream classes:

    • The Ifstream class, which is derived from the IStream class, is used to support input from a disk file.
    • The Ofstream class, which is derived from the Ostream class, is used to support output to disk files.
    • The FStream class, which is derived from the Iostream class, is used to support input and output to disk files.

To input and output a disk file for an object, you must define an object for the file stream class, output the data from memory to a disk file through a file stream object, or enter the data into memory from a file stream object from a disk file.

In fact, in the input and output of the standard device object, but also to define the flow object, such as CIN, cout is the stream object, C + + is through the stream object input and output. Since Cin and cout are already defined in the iostream.h, the user does not need to define them. When disk files are used, they cannot be defined in advance because of different circumstances, and must be defined by the user. In addition, operations on disk files are implemented through file stream objects rather than CIN and cout. File stream objects are defined by the file stream class, not by the IStream and Ostream classes. You can create an output file stream object in the following ways:
Ofstream outfile;
As with the flow object cout-defined in the header file iostream, an object outfile to the Ofstream class (output file stream Class) is now defined in the program. But there is a question that has not been resolved: when defining cout, it is associated with a standard output device (monitor), and now, although an output file stream object is established, it is not specified to which disk file it will be exported, and it needs to be specified when it is used. The next section is about to answer this question.

Opening and closing of C + + files

Here's how to open and close files on the disk, and the files on other peripherals (USB sticks, CDs, etc.) are the same.

Open File

The so-called open file is an image, like opening the door to enter the room activity. Opening a file means doing the necessary preparation before the file is read and written, including:

    • Associates a file stream object with the specified disk file so that the file stream flows to the specified disk file.
    • Specifies how the file works, such as whether the file is an input file or an output file, an ASCII file or a binary file, and so on.

The above work can be achieved in two different ways.

1) Call the file stream member function open. as
Ofstream outfile; Defines the Ofstream class (output file stream Class) object outfile
Outfile.open ("F1.dat", ios::out); Associating a file stream with a F1.dat file
The 2nd line is to call the output file stream member function open open Disk File F1.dat, and specify it as the output file, the file stream object outfile will f1.dat output data to the disk file. Ios::out is a type of I/O pattern that indicates that a file is opened in the output mode. Or simply, at this point the F1.dat is an output file that receives data from the memory output.

The general form of the call member function Open is:
File Stream object. Open (disk file name, input and output mode);
The disk file name can include a path, such as "C:\new\\f1.dat", which defaults to the file under the current directory, such as the default path.

2) Specify parameters when defining a file stream object
A constructor with parameters is defined when declaring a file stream class, which contains the ability to open a disk file. Therefore, you can specify parameters when defining a file stream object and invoke the constructor of the file stream class to implement the ability to open the file. Such as
Ostream outfile ("F1.dat", ios::out);
Generally more use this form, more convenient. The function is the same as the open function.

The input and output methods are defined in the iOS class, which are enumerated constants and have several options, as shown in table 13.6.

Table 13.6 file input and output mode setting value

Square   role
ios::in Open File as input
io S::out Opens the file as output (this is the default), if a file with this name is already in place, clear all its contents
ios::app Open the file as output, and the written data is added to the text End of piece
ios::ate Open an existing file with the file pointer to the end of the file
iOS:: trunc Open a file , if the file already exists, delete all of the data, or create a new file if the file does not exist. If you have specified the  ios::out mode and do not specify iOS:: App,ios::ate,ios:: In, this mode is also defaulted
ios:: binary in binary side Open a file, if you do not specify this method, the default is ASCII
ios::nocreate Open an existing file, if the file does not exist, the open fails. Nocrcate means not to create a new file
ios:: noreplace If the file does not exist, a new file is created and the operation fails if the file already exists,replace  Does not update the original file
ios::in l ios::out Open the file as input and output, the file can be read-write
Ios:: o UT | ios::binary Open an output file in binary mode
ios::in l ios::binar Open an input file in binary mode

A few notes:

1) ios::nocreate and Ios::noreplace are not available in the new version of the I/O class library.

2) Each open file has a file pointer, the initial position of the pointer is specified by I/O, and each read and write starts at the current position of the file pointer. Each time a byte is read, the pointer moves back one byte. When the file pointer moves to the end, you will encounter the end of the file EOF (the file terminator also takes one byte, with a value of-1), and the value of the member function EOF for the stream object is a non-0 value (typically set to 1), indicating that the file is over.

You can use the bitwise OR operator | Combine the input and output methods as shown in the last 3 rows in table 13.6. You can also cite some of the following examples:
Ios::in | iOS:: Noreplace//Open an input file and return the open failed message if the file does not exist
Ios::app | Ios::nocreate//Open an output file, then write the data at the end of the file, and if the file does not exist, returns the information that failed to open
Ios::out l Ios::noreplace//Open a new file as an output file and return the open failed message if the file already exists
Ios::in l ios::out I ios::binary//Open a binary file, readable writable

But they cannot be combined in mutually exclusive ways, such as Ios::nocreate l ios::noreplace.

If the open operation fails, the return value of the Open function is 0 (false), and if the file is opened by invoking the constructor, the value of the stream object is 0. You can test the success of the open accordingly. Such as
if (Outfile.open ("F1.bat", Ios::app) ==0)
cout << "Open error";
if (!outfile.open ("F1.bat", Ios::app))
cout << "Open error";

Close the disk File

After the read-write operation on the open disk file is complete, you should close the file. Close the file with the member function. Such as
Outfile.close (); Closes the disk file associated with the output file stream
The so-called shutdown, in effect, is to remove the disk file and file stream Association, the original set of work is also invalid, so that the file stream can no longer be input or output. You can associate a file stream with another disk file, and enter or output a new file through a file stream. Such as
Outfile.open ("F2.dat", ios::app|ios::nocreate);
At this point, the file stream outfile is associated with F2.dat and specifies how the F2.dat works.

C + + Learning 47 File concept file stream class and file stream object file open and close

Related Article

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.