A detailed description of C + + file streams

Source: Internet
Author: User
Tags readfile

Part of the content reprinted: http://blog.csdn.net/kingstar158/article/details/6859379 thanks to the pursuit of perseverance, originally wanted to write, but found so clear article.

C + + file stream operation is one of the basic content, but the content of complex, in fact, will not be difficult, here is a brief overview:

The class that needs to be called:

#include <fstream>

There are two ways to read in/out, the first of which is the flow method.

Read in:

Ifstream file ("InterestSettings.dat"); if (file) {    while ( !  File.eof ())    {        >> alive >> threemonth >> halfyear                 >> oneyear >> twoyear >> threeyear >fiveyear;    }} File.close ();

Output:

Ofstream file ("InterestSettings.dat"); if (file) {    << alive << threemonth << halfyear     << oneyear << Twoyear << threeyear << fiveyear;} File.close ();

The above Code file.eof () represents the file to the end.

Some member functions that verify the state of the stream (all return bool type return values):

    • Bad () returns true if an error occurred during the read and write process. For example: When we want to write to a file that is not open as a write state, or if the device we are writing to has no space left.
    • Fail () returns true except in the same case as bad (), plus a format error, such as when you want to read an integer and get a letter.
    • EOF () returns True if the read file reaches the end of the file.
    • Good () This is the most common: this function returns False if any of the above functions are called to return true.

To reset the status flags checked by the above member function, you can use the member function clear () without parameters.

Ifstream defaults to read the file in a ios::in way, or it can be expressed as:

FStream file ("File.dat", Ios::in)

About Ios::in, this is a switch, C + + file operation has the following switches

Ios::in Open a file for input (read)
Ios::out Open file for output (write)
Ios::ate Initial position: End of File
Ios::app All outputs appended to the end of the file
Ios::trunc If the file already exists, delete the file first
Ios::binary Binary mode

These methods are able to be used in combination with the "or" Operation ("|" ) In such a way that:

FStream deadaccountfile ("DeadAccount.dat", iOS:: in | iOS:: Out | Ios::binary);

In addition to opening the file in the constructor, you can also use the. open () function, which can be changed to the following code:

fstream deadaccountfile;deadaccountfile.open ("DeadAccount.dat", iOS:: In  | iOS:: Out | Ios::binary);

Similarly, at the end of the file use, use the. Close () function to close the file

FStream Setup ("DeadAccount.dat", iOS::out); Setup.close ();

Get and set the flow pointer

We can read or configure these flow pointers to read and write locations in the stream by using the following member functions:

Tellg () and TELLP ()

These two member functions do not pass in parameters and return a value of type Pos_type (according to the ansi-c++ Standard), which is an integer that represents the position of the current get stream pointer (with TELLG) or the position of the put stream pointer (with TELLP).

SEEKG () and SEEKP ()

This pair of functions is used to change the position of the flow pointer get and put, respectively. Two functions are overloaded with two different prototypes:

SEEKG (pos_type position);
SEEKP (pos_type position);

Using this prototype, the flow pointer is changed to point to an absolute position from the beginning of the file calculation. The parameter type required to pass in is the same as the return value type of the function Tellg and TELLP.

SEEKG (off_type offset, seekdir direction);
SEEKP (off_type offset, seekdir direction);

Use this prototype to specify a displacement (offset) to start the calculation of a specific pointer determined by the parameter direction. It can be:

Ios::beg Displacement calculated from the start of the stream
Ios::cur Displacement calculated from the current position of the flow pointer
Ios::end Displacement calculated at the end of the stream

The values of the stream pointer get and put are different for the calculation of the text file and the binary file, because some special characters in the text schema file may be modified. For this reason, it is recommended that files opened in text file mode always use the first prototype of SEEKG and SEEKP, and do not modify the return value of Tellg or TELLP. For binary files, you can use these functions arbitrarily, and there should be no unexpected behavior generated.

In binary files, using << and >>, as well as functions such as getline, to enter and output data, have little practical meaning, although they are grammatically correct. The file stream consists of two member functions that are specially designed for sequential read and write data: Write and read. The first function (write) is a member function of Ostream, which is inherited by Ofstream. Read is a member function of IStream, which is inherited by Ifstream. The objects of class fstream have both functions. Their prototypes are:

Write (char * buffer, streamsize size);
Read (char * buffer, streamsize size);

Let me show you the following example:

Output:

FStream Deadaccountfile ("DeadAccount.dat"Ios::inch| Ios:: out|ios::binary);if(!deadaccountfile) {Cerr<<"DataBase could not open"<<Endl; Exit (0);} for(inti =0; I < (int) Deadaccountarray.size (); i++) {DEADACCOUNTFILE.SEEKP (i*sizeof(Deadaccount)); Deadaccountfile.write (reinterpret_cast<Const Char*> (&Deadaccountarray[i]),sizeof(Deadaccount));}

Input:

FStream ReadFile ("SavingAccount.dat"Ios::inch| Ios:: out|ios::binary);if(!ReadFile) {Cerr<<"DataBase could not open"<<Endl; Exit (0);} Savingaccount savingaccounttemp; Savingaccountarray.clear (); for(inti =0;!readfile.eof (); i++) {READFILE.SEEKG (i*sizeof(Savingaccount)); Readfile.read (reinterpret_cast<Char*> (&savingaccounttemp),sizeof(Savingaccount));    Savingaccounttemp.setinterest (Alive); Savingaccountarray.push_back (savingaccounttemp);}

A detailed description of C + + file streams

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.