Functions of the C ++ Io stream

Source: Internet
Author: User

I. output file stream member functions

1. OPEN function of the output stream
To use Output file stream (ofstream ), Must be in The constructor or open function associates the stream with a specific disk file. . In various cases, the parameters in the description file are the same.
When you open a file associated with the output stream., you usually specify an open_mode flag, as shown in the following table. You can use the bitwise OR (|) operator to combine these flags. They are defined as enumerators in the IOS class.
Table output file stream file opening Mode
Mark Performance
IOS: The app opens an output file to add data at the end of the file.
IOS: ate open an existing file (used for input or output) and find the end
IOS: In open an input file for an ofstream file, use IOs: in as an openmode to avoid deleting the existing content in an existing file. IOS: out open two files. For output. For all ofstream objects,This mode is implicitly specified for iOS: nocreate If a file exists, open it; otherwise, the operation fails.
S: noreplace if a file does not exist, open it as a new file. If the file already exists, this operation fails.
IOS: trunc open a file. if it already exists, delete the original content. If IOS: Out is specified, but IOs :: APP and IOs: In are implicitly used in this mode.
IOS: Binary open a file in binary mode (text mode by default)
Three modes are available for public output streams:
• Create a file. If the file already exists, delete the old version:
Ostream ofile ("FILENAME"); // the default mode is IOs: Out.
Ofstream ofile ("FILENAME", IOS: Out); // equivalent to the previous sentence
• Add records to an existing file. If the file does not exist, create a new file:
Ofstream ofile ("fiilename", IOS: APP );
• Use the same stream to open different files successively (only one file is opened at the same time ):
Ofstream ofile ();
Ofile. Open ("ftile1", IOS: In) // open the file filel
... // File filel
Output ofile. Close (); // close filel
Ofile. Open ("file2", IOS: In); // open the file file2
... // Output to file file2
Ofile. Close (); // close file2
// The object ofile disappears when it leaves its scope
2. Put Function
The put function writes a character to the output stream. The following two statements are the same by default, but the second one is affected by the formatting parameters of the stream:
Cout. Put ('A'); // accurately outputs a character
Cout <"A"; // output a character, but the previously set width and fill mode work here
3. Write function
The Write function writes a piece of content in a memory to an output file stream. The length parameter indicates the number of bytes written. The following example creates an output file stream and writes the binary value of the date structure to the file:
Sample output to file
# I nclude <fstream. h>
Struct date
{
Int Mo, da, yr;
};
Void main ()
{
Date dt = {6, 10, 92 };
Ofstream tfile ("date. dat", IOS: Binary );
Tfile. Write (char *) & DT, sizeof DT );
}
The Write function does not stop when it encounters a null character. Therefore, it can write the complete class structure. This function has two parameters, one char pointer (pointing to the starting address of memory data) and the number of bytes written. Note that char * is required for forced type conversion before the address of the structure object.
4. Seekp and tellp Functions
An output file stream stores an internal pointer pointing to the next data write location. The seekp member function sets this pointer, so it can be randomly output to the disk file. The tellp member function returns the position pointer value of the file.
5. Close function of the output stream
Close the member function to close the disk file associated with an output file stream. After the file is used, it must be closed to complete all disk output. Although the ofstream destructor will be automatically closed, if you need to open another file on the same class object, you need to use the close function.
If the constructor or open member function opens the file, the output stream destructor automatically closes the file of a stream.
6. error handling functions
The error handling member function is used to handle errors when writing data to a stream. The functions and functions are shown in the following table.
Error Handling member functions
Function and Return Value
Bad: if a non-recoverable error occurs, a non-zero value is returned.
Fail returns a non-zero value if a non-recoverable error or an expected condition occurs, such as a conversion error or the file is not found. Clear may be restored frequently after being called with zero parameters.
Good if there are no error conditions (unrecoverable or other) and no end mark of the file is set, a non-0 value is returned.
EOF returns a non-zero value if the file end condition is met.
Clear sets the internal error status. If the default parameter is used, all error bits are cleared.
Rdstate returns the current error status

! The operator is overloaded. It performs the same functions as the Fail function, so the expression if (! Cout) is equivalent to If (cout. Fail ()).
The void * () operator is also overloaded, and! The opposite operator, so the expression if (cout) is equivalent to If (! Cout. Fail ()).
The void * () operator is not equivalent to good because it does not detect the end of a file.
(4) binary output file
The original design flow is used for text, so the default output mode is text. When output in text mode, if a line break (decimal 10) is encountered, it is automatically expanded to a carriage return line break (decimal 13 ). This automatic expansion may cause problems. Please refer to the following Program :
# I nclude <fstream. h>
Int iarray [2] = {99,10 };
Void main ()
{
Ofstream OS ("test. dat ");
OS. Write (char *) iarray, sizeof (iarray ));
}

When the execution program outputs data to the file, 10 is automatically converted to 13. However, the conversion here is obviously not what we need. To solve this problem, we need to use the binary mode output. When binary mode is used for output, the characters in the output are not converted. The following methods can be used to output data to a file in binary mode,
(1) construct a stream in the usual way, and then use the setmode member function to change the mode after the file is opened. For example:
Ofstream ofs ("test. dat ");
OFS. setmode (filebuf: Binary );
OFS. Write (char *) iarray, 4); // write 4 bytes of data to the binary file
(2) Use the mode parameter in the ofstream constructor to specify the binary output mode. For example:
# I nclude <fstream. h>
# I nclude <fcntl. h>
# I nclude <Io. h>
Int iarray [2] = {99,10 };
Void main ()
{
Ofstream ofs ("test. dat", IOS: Binary );
OFS. Write (char *) iarray, 4); // write 4 bytes of data to the binary file
}
(3) Use a binary operator to replace the setmode member function:
OFS <binary;
If the text operator is used, the stream is switched to the text conversion mode.
(4) use the open function with a binary mode flag to open the file, for example:
Filedesc FD = open ("test. dat", obinary | ocreat | owronly );
Ofstream ofs (FD );
OFS. Write (char *) iarray, 4); // write 4 bytes of data to the binary file

Ii. input stream member functions

The input member function is used to input data from a disk file. These member functions include:
• Open Functions
• Get Function
• Getline Function
• READ function
• Seekg and tellg Functions
• Close Function
1. OPEN function of input stream
To use an input file stream (ifstream), you must use the constructor or open function to associate the stream with a specific disk file. Either way, the parameters are the same.
When you open a file associated with an input stream, you must specify a mode flag. The Pattern mark is shown in the following table. It can be combined using the bitwise OR (|) operator.
Table input file stream file opening Mode
IOS: In open the file for input (default)
IOS: nocreate if the file does not exist, this function fails.
IOS: Binary open files in binary mode (text mode by default)
Note: To test whether a file exists, you must specify the IOS: nocreate mode when opening the file, and then use the Fail member function to confirm:
Istream ifile ("FILENAME", IOS: nocreate );
If (ifile. Fail ())
// The file does not exist...
2. Get Function
The functions of the unformatted get function are similar to those of the extract operator (>). The main difference is that the get function contains blank characters when reading human data, by default, the extract operator rejects white spaces.
Example of get Function Application
# I nclude <iostream. h>
Void main ()
{
Char ch;
While (CH = cin. Get ())! = EOF)
Cout. Put (CH );
}
If you enter:
Abc xyz 123
Output:
Abc xyz 123
3. Getline Function
The Getline member function allows you to read multiple characters from the input stream, and allows you to specify the input termination character (the default value is a line break character). After reading, delete the ending character from the read content.
For example, specify a termination character for the input stream.
This program continuously reads a string of characters until it stops when the character 't' is encountered. The maximum number of characters cannot exceed 99.
# I nclude <iostream. h>
Void main ()
{
Char line [100];
Cout <"Type A 1ine terminated by" T "" <Endl;
Cin. Getline (1ine, 100, "T ");
Cout <line;
}
4. Read Function
The read member function reads bytes from a file to a specified storage area. The length parameter determines the number of bytes to be read. If the length parameter is provided, the read ends when the file ends or the end mark character is encountered in the text mode file.
For example, read a binary record from a payroll file to a structure.
# I nclude <Io. h>
Void main ()
{
Struct
{
Double salary;
Char name [23];
} Employee;
Ifstream is ("payroll", IOS: Binary | IOs: nocreate );
If (is)
{
Is. Read (char *) & employee, sizeof (employee ));
Cout <employee. Name <"" <employee. Salary <Endl;
}
Else
{
Cout <"error: cannot openfile" payroll "." <Endl;
}
}
It is assumed that the data record is strictly formatted by the specified structure, and there is an ending carriage return or line feed character.
5. seekg and tellg Functions
In the input file stream, an internal pointer pointing to the next location in the file to read data is retained. You can use the seekg function to set this pointer.
For example, use the seekg function to set the position pointer.
# I nclude <fstream. h>
Void main ()
{
Char ch;
Ifstream tfile ("payroll", IOS: Binary | IOs: nocreate );
If (tfile)
{
Tfile. seekg (8 );
While (tfile. Good ())
{
// End the read operation when the file ends or the read operation fails.
Tfile. Get (CH );
If (! Ch) break; // exit the loop if it is not read.
Cout <ch;
}
}
Else
{
Cout <"error; cannot open file" payroll "." <Endl;
}
}

You can use seekg to implement a record-oriented data management system. Multiply the fixed length record size by the record number to get the byte position relative to the end of the file, and then use get to read the record.
The tellg member function returns the position of the read pointer of the current file. The value is of the streampos type. The typedef structure is defined in iostream. h.
For example, read a file and display the space position.
# I nclude <fstream. h>
Void main ()
{
Char ch;
Ifstream tfile ("payroll", IOS: Binary | IOs: nocreate );
If (tfile)
{
While (tfile. Good ())
{
Streampos here = tfile. tellg ();
Tfile. Get (CH );
If (CH = "")
Cout <"\ nposition" }
}
Else
{
Cout <"error: cannot open file" payroll "." <Endl;
}
}
6. input stream close Function
Close the member function to close the disk file associated with an input file stream.
Although the destructor of the ifstream class can automatically close the file, if you need to use the same stream object to open another file, use the close function to close the current file first.
Iv. Input/output streams
An iostream object can be the source or destination of data. Two important I/O Stream classes are derived from iostream, which are fstream and strstream. These classes inherit the functions of the stream and ostream classes described above.
Fstream supports the input and output of disk files. If you need to read and write files from a specific disk file to the same program, you can construct an fstream object. An istream object is a single stream with two logical sub-streams. One of the two sub-streams is used for input and the other for output. For more information, see the online help or running database reference manual.

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.