C ++ Io standard library file operations

Source: Internet
Author: User
Tags setf

From: http://hi.baidu.com/luckymouse2009/blog/item/80042808ee129da62fddd47e.html

 

   
C ++ Io standard library file operations

Write a small program that reads and writes files in a stream at the same time.

String login, user;
Fstream logfile ("log. dat", fstream: In | fstream: Out | fstream: trunc );
If (! Logfile)
{
Exit (-1 );
}
Logfile <"Danny is pig" <Endl; // write a new record.
Logfile <"you are right" <Endl;
// Int off = logfile. tellp ();
Logfile. seekp (IOs: Beg); // reset the location
Logfile> login> User; // read the previously written Value

Cout <login <user <Endl;
// Logfile. seekp (Off, IOS: Beg );
For (INT I = 0; I <10; I ++)
{
Logfile <"you are dog" <Endl;
}

At the beginning, I didn't write the two comments. The result "you are dog" cannot be written into the file. It is estimated that the file pointer does not know where to go. After adding these two statements, you can restore the previously written position before writing the statement. It is not clear where the specific pointer is. If you know the internal details, please let me know.

The following are some tips on this topic.

This article mainly discusses the C ++ standard I/O Library, including the console input and output streams, file streams, and string streams.

If there are any errors or omissions in this article, please point out. Thank you!

Stream Introduction
Standard I/O Class header files
<Iostream> contains three classes: istream, ostream, and iostream. Iostream is derived from istream and ostream.
<Fstream> contains ifstream, ofstream, and fstream classes. Ifstream is derived from istream, ofstream is derived from ostream, and fstream is derived from iostream.
<Sstream> includes three classes: istringstream, ostringstream, and stringstream. Istringstream is derived from istream, ostringstream is derived from ostream, and stringstream is derived from iostream.

Note: The standard library I/O objects cannot be copied or assigned values.
The complete Relation Diagram of the stream class in the C ++ standard library is as follows: (Note: When I find a problem, the following figure shows fuzzy information when I open a webpage. The displayed figure is smaller than the actual one, there are two methods: one is to refresh the image several times, and the other is to display the picture ^_^)

Among them, typedef basic_ios <char, char_traits <char> Ios;
Typedef basic_istream <char, char_traits <char> istream;
Typedef basic_ostream <char, char_traits <char> ostream;
Typedef basic_iostream <char, char_traits <char> iostream;
Typedef basic_istringstream <char> istringstream;
Typedef basic_ostringstream <char> ostringstream;
Typedef basic_stringstream <char> stringstream;

Stream status

Ios_base: the integer type name related to the iostate machine. It is used to define the stream status. The basic class IOS of the I/O standard library defines four flag spaces of this type for static members:
Ios_base: badbit this flag indicates that the I/O Stream has encountered a serious error (it often refers to physical damage and cannot be corrected)
Ios_base: eofbit this flag indicates that the I/O Stream has reached the end of the file
Ios_base: failbit this flag indicates that the I/O Stream has failed I/O operations.
Ios_base: goodbit indicates that the I/O Stream is normal.

Note: Each flag can be connected using the | Operator. For convenience, you can use IOS instead of ios_base to use these flag spaces (the flag is a static constant member of ios_base ), the ios_base shown in the following content can also be used.

Detect stream status:
IOS: Bad (): If the badbit flag of the stream is set, true is returned; otherwise, false is returned.
IOS: EOF (): If the eofbit flag of the stream is set, true is returned; otherwise, false is returned. If eofbit is set, failbit is also set.
IOS: fail (): If the stream's failbit flag is set, true is returned; otherwise, false is returned.
IOS: Good (): If the goodbit flag of the stream is set, true is returned; otherwise, false is returned. Good () returns true only when both bad (), EOF (), and fail () return false.

In addition to directly calling these member functions of the stream to detect the stream status, we can also use the stream object directly in a Boolean expression for testing. For example:
Int I;
While (CIN> I)
Cout <I <Endl;
In this case, the operator void * () conversion to the void * type is implicitly called, and then implicitly converted to the bool type.

Why does a stream class not directly define an implicit conversion to the bool type? This is because this may cause errors. Because the bool type can be implicitly converted to the int type, so that the stream class object can be implicitly converted to the int type, it is very easy to reference errors. For example, if you want to input "CIN> I", but actually input "CIN> I", a ">" is missing. If there is an implicit conversion from a stream object to bool, the syntax of "CIN> I" is correct, which is equivalent to the final comparison of two int types. Obviously, we do not want this to happen. In addition, for historical reasons, the bool type does not exist in the first C ++, so it is converted to the void * type.

Set/get stream status:
Ios_base: clear (state): sets the s flag of the stream to state. The default parameter is goodbit.
Ios_base: setstate (state) adds the specified flag State for stream S. The original flag still exists, which is equivalent to calling clear (state | rdstate ())
Ios_base: rdstate () returns the current flag of stream S.

Manage the output buffer

In the following situations, the content in the output buffer is refreshed to the output device or file:
1) The program ends normally. As part of the main return work, all output buffers will be cleared;
2) When there are some uncertainties, the buffer may be full. In this case, the buffer will be refreshed before the next value is written;
3) use the operator (Manipulator) to explicitly refresh the buffer, such as Endl and flush;
4) after each output operation is executed, use the unitbuf operator to set the internal status of the stream to clear the buffer;
5) the output stream can be associated with the input stream (TIE. In this case, when reading the input stream, it will refresh its associated output stream buffer.

The following lists the operators used to refresh the buffer:
The Endl operator outputs a linefeed and refreshes the buffer.
The ends operator outputs a NULL Character and refresh the buffer.
The flush operator refreshes the buffer directly without adding any characters.
The unitbuf operator refreshes the buffer after each write operation.

For example:
Cout <unitbuf <"first" <"second" <nounitbuf;
It is equivalent:
Cout <"first" <flush <"second" <flush;
The nounitbuf operator restores the stream to a normally used, system-managed buffer refresh method.

Associate input and output with the tie function:
Basic_ostream <E, T> * Tie () const;
Basic_ostream <E, T> * Tie (basic_ostream <E, T> * Str );

The tie function can be called by istream or ostream objects and uses a pointer to an ostream object. The first function returns the previously stored associated ostream Object Pointer. The second function sets a new associated object and returns the pointer of the previously associated object. If the parameter of the second function is 0, the association between two objects is broken. For example:
Cin. Tie (& cout); // tie CIN and cout
Ostream * old_tie = cin. Tie ();
Cin. Tie (0); // break tie between CIN and cout
Cin. Tie (& ERR); // a new tie
Cin. Tie (old_tie); // restablish tie between CIN and cout

File stream

If the file stream has been associated with a specified file, to associate the file stream with another file, you must close the current file before opening it) another file. The open function checks whether a file has been opened. If yes, the failbit flag is set to indicate an error, and any read/write operations on the file stream will fail. In this case, you can clear the flag and continue to operate on the previous file.
File Mode

Ios_base: In Read mode
Ios_base: Out write mode
Ios_base: append Mode
Ios_base: locate the end Of the file immediately after opening the file.
Ios_base: clears the file content when trunc opens the file (if any)
Ios_base: Binary open a file in binary mode

The above flag is declared as a static constant Member of the ios_base class. The out, Truc, and app modes can only be used for files associated with the ofstreamt and fstream objects; the in mode can only be used for files associated with ifstreamt and fstream objects; the ATE and binary modes can be used for all files.

If a file is opened in binary mode, the file stream processes the file content in a byte sequence without any explanation. Otherwise, the file is opened in text mode by default, different systems may interpret and convert the file content. For example, in a non-Unix system, such as a Windows system, line breaks/n are interpreted as carriage breaks/R/N to the file system, /R/N is interpreted as/N to memory. In Unix systems, there is no difference between the binary mode and the text mode.

By default, files associated with ifstream stream objects are opened in mode, and files associated with ofstream are opened in out mode, in addition, the content of files opened in out mode will be cleared (equivalent to the trunc mode is also specified); files associated with fstream will be opened in and out mode.

If the out mode is used when opening the file associated with fstream, but the in mode is not specified, the file content will be cleared. If the trunc mode is specified, whether or not the in mode is specified, all files are cleared.

Effective Combination of file Modes
Open the file out and perform the write operation to delete the existing data in the file. If the file does not exist, create the file.
The app opens the file for write operations and appends data at the end of the file. If the file is associated with the ofstream stream, the file is created when the file does not exist. If the file is associated with the fstream stream, the operation fails if the file does not exist.

Out | append data to the app. If the file does not exist, create the file.
Out | the trunc and out modes are the same.
In to open the file for read Operations

In | out open the file for read and write operations, and locate it at the file header
In | Out | trunc opens the file for read and write operations, and deletes existing data in the file

String stream

String stream defines a constructor that uses string objects as parameters. The read and write operations on the sstream object are actually performed on the string object in the object.

The sstream class also defines a member named STR () to read or set the string object manipulated by the sstream object.
Basic_string <E, T, A> STR () const;
Void STR (basic_string <E, T, A> & X );

Common usage of string stream

It is used to format data input and output, which is equivalent to the fscanf and fprintf functions in C language. For example:

Int var1 = 5, var2 = 10;
Stringstream SS;
SS <"var1:" <var1 <"var2:" <var2;
Cout <"SS <:" <ss. STR () <Endl;
Var1 = var2 = 0;
String dump;
SS> dump> var1> dump> var2;
Cout <"SS>: var1:" <var1 <", var2:" <var2 <Endl;

--------------------------------------------------------------------------------

Stream formatting I/O
Operator

The operator defined in <iostream> (the asterisk (*) is used by default)
Boolalpha returns true and false as strings
* Noboolalpha displays true and false
Base prefix of the number of showbase instances
* Noshowbase does not generate the base prefix of the number.
Showpoint always displays decimal places
* The noshowpoint has a decimal point.
Showpos displays + (0 also displays +) in non-negative values)
* Noshowpos does not show + of non-negative values
Uppercase prints 0x in hexadecimal notation and E in scientific notation
* Nouppercase prints 0x in hexadecimal notation and E in scientific notation
* DEC is displayed in decimal format.
Hex display in hexadecimal format
Oct display in octal Mode
Left is aligned, and fill characters are added to the right of the value.
* Right: The right alignment. Add a filling character to the left of the value.
Internal alignment, fill in characters between values and symbols
Fixed displays floating point numbers in decimal form
Scientific displays floating-point numbers in scientific notation
Flush refresh ostream Buffer
Ends inserts null characters and refresh the ostream buffer.
Insert a linefeed to the Endl and refresh the ostream buffer.
Unitbuf refreshes the buffer after each output operation
* Nounitbuf resumes regular buffer refresh
* Skipws is the input operator> skips blank characters (spaces, tabs, and line breaks)
Noskipws does not skip blank spaces for input operators
WS "eat" Blank

By default, the period used to display floating-point numbers depends on the size of the number. If the number is large or small, it is displayed in scientific notation; otherwise, it is displayed in decimal places with a fixed number of digits.

If scientific or fixed is set, because there is no corresponding operator to restore the default value, you can only call the unsetf member to cancel the changes made by scientific or fixed: unsetf (ios_base: floatfield ); (function prototype: void unsetf (fmtflags mask );)

Operator defined in <iomanip>

Setfill (char ch)
Setprecision (int n) sets the floating point precision to n
SETW (int w) reads and writes data of W characters
Setbase (int B) Outputs An integer based on the base B. The N values are 8, 10, and 16. If it is another value, the base is 10.
Setiosflags (ios_base: fmtflags N) is equivalent to calling SETF (n)
Resetiosflags (ios_base: fmtflags N) clears the format flag represented by N.

By default, the precision specifies the total number of digits (before and after the decimal point). The default value is 6 digits. After fixed or scientific is used, the precision is the number of digits after the decimal point.

SETW does not change the stream status and is only valid for the next data output. After other operators change the stream format status, the I/O Stream retains the changed format status.

Flag member functions

The IOS class provides the flag member function to set and restore the format status of the stream (all flags). The function prototype is as follows:
Ios_base: fmtflags flags () const; // return the current format status of the stream.
Ios_base: fmtflags flags (ios_base: fmtflags fmtfl); // you can specify the stream format status.

SETF and unsetf member functions

The IOS class provides these two member functions to set or cancel a flag. The function prototype is as follows:
Void SETF (ios_base: fmtflags mask );
Ios_base: fmtflags SETF (ios_base: fmtflags fmtfl, fmtflags mask );
Void unsetf (ios_base: fmtflags mask); // clear the specified flag

Among them, the first SETF version applies to the switch flag. These switch flags include:
Ios_base: boolalpha, ios_base: skipws, ios_base: showbase, ios_base: showpoint, ios_base: uppercase, ios_base: showpos, ios_base: unitbuf
The second SETF version is applicable to formatting the domain flag. Only one of these flags can be set at a time. The format fields and their flags are as follows:
Ios_base: basefield: ios_base: Dec, ios_base: Hex, ios_base: Oct
Ios_base: floatfield: ios_base: Scientific, ios_base: fixed
Ios_base: adjustfield: ios_base: Left, ios_base: Right, ios_base: Internal

For example,
S. SETF (ios_base: boolalpha); // you can specify the Boolean value as a character.
S. seft (ios_base: Scientific, ios_base: floatfield); // set the fractional output form to scientific notation
S. unsetf (ios_base: floatfield); // clear the flag of the floatfield Field

Other member functions

The IOS class also provides several other member functions to control the output domain format. The function prototype is as follows:
Int ios_base: width (); // returns the current width. The default value is 0.
Int ios_base: width (int n); // set the width.
Char IOs: Fill ();
Char IOs: Fill (char N );
Int ios_base: precision ();
Int ios_base: precision (int n );

--------------------------------------------------------------------------------
Unformatted input/output operations of a stream
Single-byte operation

Is. Get (CH) puts the next byte of istream is into the CH, and returns the is
OS. Put (CH) puts the byte CH in ostream OS and returns the OS
Is. Get () returns the next byte of is as an int value.
Is. putback (CH) puts the character ch back to is and returns is
Is. unget () returns is to a byte and returns is
Is. Peek () returns the next byte as the int value but does not remove it (does not move the stream buffer pointer)

In general, it is guaranteed that a maximum of one value can be put back before the next read. That is to say, it is not guaranteed that putback or unget can be called continuously to restore the original stream status.

Why should get () and peek () return the int type instead of the char type? The reason is that a file Terminator is allowed to be returned. Given that each value in the char range is allowed to represent the actual character set, no additional value in the range is used to represent the file Terminator. Instead, these functions convert characters to unsigned char and then increase that value to int. Therefore, even if the character set has a character mapped to a negative value, the value returned from these operations will also be a positive value. By returning a file Terminator as a negative value, the standard library ensures that the file Terminator is different from any valid character value. The file Terminator EOF is defined in the <iostream> file as a negative value of the const variable. It is used to indicate whether the file ends. For example:
Int ch; // int, not Char!
While (CH = cin. Get ())! = EOF)
Cout. Put (CH );

Multi-byte operations

Is. Get (BUF, size, delim). Its function prototype is:
Basic_istream & get (E * s, streamsize N, e delim = '/N'); read size bytes from is and store them in the space pointed to by BUF, returns is. When a read operation encounters a delim character, a file Terminator, or a size byte, the read operation ends. If delim is encountered, it will be left in the input stream.
Is. Getline (BUF, size, delim). Its function prototype is:
Basic_istream & Getline (E * s, streamsize N, e delim = '/N'); similar to the get action above, the difference is to read and discard delim.
Is. Read (BUF, size) reads size bytes to Buf, returns is
Is. gcount () returns the number of bytes read from the stream is by the last unformatted read operation.
OS. Write (BUF, size) writes the size bytes from the array Buf to the OS, and returns the OS
Is. Ignore (size, delim) reads and ignores size characters until delim is encountered, but delim is not included. The default size parameter is 1, and the default delim parameter is the file Terminator.

Because the single-character operation that puts the character back is not formatted, if you call peek, unget or putback before calling gcount, the return value is 0.

For example, if an error occurs in the input buffer and the buffer needs to be cleared, you can do this:
If (! CIN ){
Cin. Clear ();
Cin. Ignore (numeric_limits <int>: max (), '/N ');
}
In addition, it should be noted that low-level I/O operations are prone to errors, and the advanced abstraction of standard libraries is recommended. For example, an I/O operation that returns an int value is a good example.

It is a common error to assign the return values of get or other functions that return int values to Char objects instead of int objects. For such errors, the specific behavior on the machine depends on the machine and input data. For example, on a machine that implements char as unsigned char, this is an endless loop:
Char ch;
While (CH = cin. Get ())! = EOF)
Cou. Put (CH );
This is because when get returns EOF, the value will be converted to the unsigned char value, and the converted value will not be equal to the EOF integer value, forming an endless loop.

--------------------------------------------------------------------------------
Random stream access
The I/O Stream provides two member functions for random access: the location function (seek) and the query function (tell ). See the following table:
Seekg relocates the read pointer tellg in the input stream returns the current position of the read pointer in the input stream seekp relocates the write pointer tellp in the output stream returns the current position of the write pointer in the output stream
Note: In each stream (even the stream that can be input and output at the same time, such as fstream), there is only one read (write) pointer, the standard library maps both the G position and the P position to this pointer. Therefore, when switching between reading and writing, seek must be performed to relocate the tag.

In addition, because the istream and ostream types generally do not support random access, random access to the stream is only applicable to the fstream and sstream types.

Seekg and seekp both have two overloaded versions. One uses an absolute address and the other uses a relative offset. The function prototype is as follows:
Basic_istream & seekg (pos_type POS );
Basic_istream & seekg (off_type off, ios_base: seek_dir way );
Basic_ostream & seekp (pos_type POS );
Basic_ostream & seekp (off_type off, ios_base: seek_dir way );

In the above function, the way parameter has several predefined values:
Ios_base: Beg indicates the beginning of the stream
Ios_base: cur indicates the current stream position
Ios_base: end indicates the end of the stream.
In addition, seek_dir, pos_type, and off_type are all types in the ios_base class.

Below are two tell function prototypes:
Pos_type tellg ()
Pos_type tellp ();
--------------------------------------------------------------------------------

Stream class and exception
In addition to manually checking the stream status, you can also use the exception mechanism to solve stream errors. The member function exceptions () of the stream accepts a parameter, which indicates the stream status flag that the programmer wants to throw an exception when it appears. When a stream encounters such a state, it throws an STD: ios_base: failure type exception, which is inherited from STD: exception. The function prototype is as follows:
Iostate exceptions () const;
Iostate exceptions (iostate failed t );
-----------------------------------------------------------------------------
If there are any errors or omissions in this article, please point out. Thank you!
------------------------------------------------------------------------------
References:
[1] C ++ primer (Edition 4)
[2] thinking in C ++ (Volume Two, Edition 2)
[3] international standard: ISO/IEC 14882: 1998

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.