C/C ++Input and output stream Summary
When I wrote my c ++ internship assignment two days ago, I suddenly found that I/O was so strange that I/O files were not opened for a long time. Today, I finally decided to find a book, sort it out and share it with you.
C ++ I/O
C ++ supports two types of I/O. The first one is inherited from the C language, and the other is an object-oriented I/O system defined by C ++.
1. Int getchar (void); returns an integer. You can also specify this value as a char variable because this character is contained in the low byte (the high byte is usually 0 ), if there is an error, getchar () returns EOF. However, he has a potential problem. Normally, getchar () caches the input until the Enter key is typed. (this should be a deep understanding, that is, getchar () seems to only know the Enter key, this is the reason.) This is called row buffer input. You must enter a carriage return key before the characters you have typed are actually transmitted to the program.
2. Int putchar (int c );
Although putchar () has an integer parameter, it can be called with a variable of a character, but only its low byte is actually output to the screen, putchar () the function returns the written characters. If the operation fails, the returned EOF is defined as stdio. in H, the value is usually-1 ).
3. Int getch (void );
Int getche (void );
Two of the most commonly used interactive functions, for most compilers, the prototype of these functions can be found in the header file conio. H. For Some compilers, these functions are preceded by an underscore. Such as _ getch () and _ getche (); that is why a '_' is often prompted in vs2008 '_'.
4. char * gets (char * Str );
Read the input string from the keyboard and store it in the address indicated by another variable. It reads characters from the keyboard until a return key is encountered. The enter key does not enter a part of the string. Instead, it places the null terminator at the end of the string and is returned by gets. However, be careful when using gets () because it does not perform a boundary check on the Character arrays that are being input. Therefore, you can enter more characters than the array can accommodate. Although it is good for your sample programs and simple tools, it is generally not used in commercial code. Its alternative is fgets (); described later.
5. Int puts (const char * Str );
Write the variable string to the screen, followed by a new line. It has lower overhead than printf (), because puts () can only input strings and cannot output numbers or convert formats. Therefore, puts () it uses less space and is faster than printf. Therefore, the function puts () is often used for code optimization. If the operation fails, the function puts () returns EOF; otherwise, a non-negative value is returned.
6. Int printf (const char * control_string ,...);
The printf () function returns the number of written characters. If an error occurs, the return control_string contains two types of items. The first type is composed of strings that will be printed on the screen, and the second type includes format delimiters for customizing the display mode of the variable elements. The format qualifier starts with a percent sign followed by a formatting code. The number of elements in the Yuan list is exactly the same as the format qualifier, and the format qualifier matches the yuan in order from left to right.
7. Int scanf (const char * control_string ...);
You can read various embedded types and automatically convert them to the appropriate format. If the returned result is successful, a data item with a value is assigned. If an error occurs, scanf () returns EOF. The control string contains three types of characters:
A. Format qualifier B, white space character C, non-white space character
The format qualifier starts with a percent sign and tells scanf () What type of data to be read next.
8. File * fopen (const char * filename, const * char * Mode)
Open a file
The valid mode values are as follows:
R open a text file for a read operation
W. Create a text file for the write operation
A appended to a text file
RB opens a binary file for the read operation
WB creates a binary file for the write operation
AB appended to a binary file
R + opens a text file for read/write operations
W + creates a text file for read/write operations
A + attaches or creates a text file for read/write operations
R + B opens a binary file for read/write operations
W + B creates a binary file for read/write operations
A + B attaches a binary file to read/write operations
If the file fails to be opened, fopen () returns a null pointer.
9. Int fclose (File * FP );
Close a file opened by fopen (), write the data left in the disk buffer to the file, and officially close the file at the operating system level. Disabling streaming files may cause various troubles, such as data loss, file damage, and intermittent errors in programs. Flose () also releases control blocks with stream files so that they can be reused. Sometimes, because the operating system opens a limited number of files at a time, you must close a file before opening another file. The return value 0 indicates that the file is successfully closed. If the function fails to be disabled, EOF is returned. Standard function ferror () can be used to determine and report error messages. In general, an error is reported when fclose () is removed too early in the drive on the disk or when there is no more space on the disk.
10. Int putc (int ch, file * FP );
Write a character to a file. If the operation succeeds, the function returns the output bytes. Otherwise, the system returns the EOF
11. Int GETC (File * FP );
When a character is read from a file and the function GETC () reads the end of the file, the EOF flag is returned. If an error occurs, the EOF is also returned.
12. fgetc (), same as GETC ()
13. Int fgets (const char * STR, int length, file * FP); read a string from a file until it reads the line break or reads the length-1 character, if a new row is read, it is a part of the original string (unlike gets (), and the result string is terminated with null. If the operation succeeds, the function returns STR; otherwise, a null pointer is returned.
14. Int fputs (const char * STR, file * FP): writes the string pointed to by STR to the specified stream. If it fails, the EOF
15. fseek (): Find a specific byte in the file
16. ftell () returns the location of the current file
17. fprintf () is output to the disk file.
18. fscanf (), read data from the disk
19. Int feof (File * FP );
Returns the true value at the end of a file. It can be used either as a binary file or as a text file.
Eg:
While (! Feof (FP) CH = GETC (FP );
20. Int ferror (File * FP );
The function determines whether an error occurs during file operations. FP is a valid file pointer. If an error occurs during file operations, the function returns true; otherwise, false. Because error conditions are set for each file operation, you should call ferror () immediately after the operation in each file; otherwise, the error message will be lost.
21. Void rewind (File * FP) puts the file position pointer at the beginning of the file. FP is a valid file pointer,
22. Int remove (const char * filename): clears a file. If the operation is successful, 0 is returned. If the operation fails, a non-zero value is returned.
23. Int fflush (File * FP );
Clears the content of an output stream and writes the content of any buffer to files related to FP. If fflush () is called when FP is empty (), all files opened for the output are cleared. If the operation is successful, 0 is returned; otherwise, EOF is returned.
24, size_t fread (void * buffer, size_t num_byte, size_t count, file * FP );
Buffer is a pointer pointing to the storage area of the data in the receiving file. The Count value indicates the number of items to be written. Returns the number of read items, such as the end of a file or an operation failure. This value may be less than count.
25. size_t fwrite (const void * buffer, size_t num_byte, size_t count, file * FP );
Buffer is a pointer pointing to the information in the file to be written. The value of count indicates the number of items to be written. Returns the number of write items. This value is always equal to count unless the operation fails.
Note: The size_t type is defined as an unsigned integer. FP is a file pointer to an opened stream. One of the greatest uses of fwrite () and fread () is to write user-defined data types, especially struct types.
26. Int fseek (File * FP, long int numbytes, int origin );
FP is the pointer returned by fopen (). numbytes is the byte from the file origin location to the current location. It is one of the following macros:
Origin macro name
Seek_set at the beginning of the file
Current location seek_cur
Seek_end at the end of the file
You can use fseek () to find a multiple of any data type by multiplying the expected number of items by the length of the data. Eg: fseek (FP, 9 * sizeof (struct mystruct), seek_set );
27. Long int ftell (File * FP );
Determines the current location of a file and returns the address of the current location of the file associated with FP. If it fails,-1 is returned.
28. Int fprintf (File * FP, const char * control_string ...);
Int fscanf (File * FP, const char * control_string ...);
Note: Although fprintf () and scanf () are the easiest way to read and write data from disk files, they are not the most effective method. Because the format of formatted ASC ⅱ data written to the file is the same as that displayed on the screen (rather than in binary mode), additional overhead is required during the call. If you want to consider speed and file length, it is best to use fread () and fwrite ()
C ++ built-in stream
Stream meaning default device
Cin Standard Input Keyboard
Cout standard output screen
Cerr standard error output screen
Clog cerr buffer version screen
The stdin, stdout, and stderr of CIN, cout, cerr, and C correspond to each other.
C ++ additional streams: Win, wout, werr, and wlog are all standard streams of character versions. The wide character type is wchar_t, which is generally 16 bits.
29. fmtflags SETF (fmtflags flags );
This function returns the flag of the previous format and enables the flag specified by flags.
Eg:
Cout. SETF (IOs: showpoint );
Cout. SETF (IOs: showpos );
Or cout. SETF (IOs: showpoint | IOs: showpos );
30. Void unsetf (fmtflags flags );
The flag specified by flags is cleared.
Eg:
Cout. SETF (IOs: uppercase | IOs: scientfic );
Cout. unsetf (IOs: uppercase );
31. fmtflags flags ();
Returns the current position marked in each format.
32. fmtflags flags (fmtflags F );
Set all tags of a stream.
Eg:
IOS: fmtflags F = IOs: showpos | IOs: showbase | IOs: Oct | IOs: right;
Cout. Flags (f); // set all flags
33. streamsize width (streamsize W );
Modify the minimum domain width. W indicates the domain width to be changed. The previous domain width is returned.
34. streamsize precision (streamsize P );
When the floating point type is output, you can use the precision () function to determine the exact number of digits.
35. Char fill (char ch );
Fill in the specified character, which is a space by default
C ++ Operator
Operation operator purpose input/output
Boolapha enables boolapha to mark input/output
Enable dec mark output in Dec
Endl outputs a line break and refreshes the stream output.
Ends outputs a null output.
Fixed enable fixed flag output
Flush refresh a stream output
Enable hex to mark output/Input
Enable internal mark output
Left enables left flag output
Noboolalpha close noboolalpha mark input/output
Noshowbase disable showbase flag output
Noshowpoint close showpoint mark output
Noshowpos disable showpos flag output
Noskipws disable skipws flag Input
Nounitbuf disable unitbuf flag output
Nouppercase close uppercase mark output
Enable Oct to mark input/output
Resetiosflags (fmtflags f) disable the specified flag input/output in F.
Right enable right flag output
Scientific enable scientific mark output
Setbase (INT base): Set the base to base input/output.
Setfill (INT ch): Set the padding character to Ch output.
Setiosflags (fmtflags f) enables the specified tag input/output in F.
Setprecision (int p)
SETW (int w) sets the field width to W output
Showbase enabling showbase flag output
Showpoint enabling showpoint flag output
Showpos enabling showpos flag output
Skipws enable skipws flag Input
Unitbuf enables unitbuf to mark output
Uppercase enable uppercase flag output
WS skips the start space Input
Note: when accessing the operator with parameters, you must include <iomanip> in the program.
Create your own plug-in:
Ostream & operator <(ostream & stream, class_type OBJ)
{
// Body of inserter
Return stream;
}
Create your own analytics
Istream & operator> (istream & stream, class_type OBJ)
{
// Body of extractor
Return stream;
}
Input and Output of C ++ files <fstream>
Create a stream
Ifstream in; // Input
Ofstream out; // output
Fstream IO; // Input and Output
36,
Void ifstream: open (const char * filename, IOS: opennode mode = IOs: In );
Void ofstream: open (const char * filename, IOS: openmode mode = IOs: Out | IOs: trunc );
Void fstream: open (const char * filename, IOS: openmode mode = IOs: In | IOs: Out );
Openmode:
IOS: app adds all the content output to the corresponding file to the end of the file. This value can only be used for files with the output function.
IOS: ate allows you to locate the end Of the file when opening the file.
IOS: binary files can be opened as binary files. By default, all files are opened as text files.
IOS: In is specified as input.
IOS: Out specifies my output
IOS: trunc destroys the content of the previous file with the same name, and truncates the file length to 0, when an output stream is created using ofstream, any previously existing files with this file name will be automatically truncated.
Eg:
If (! Mystream)
{
Cout <"cannot open file. \ n ";
// Handdle Error
}
If (! Mystream. is_open ())
{
Cout <"cannot open file. \ n ";
// Handdle Error
}
37. istream & get (char & Ch );
Ostream & put (char & Ch );
Eg:
While (in. Get (CH ))
Cout <ch;
38. istream & read (char * Buf, streamsize num );
Ostream & write (const char * Buf, streamsize num );
The read () function reads num characters from the stream and puts them into the buffer zone referred to by the Buf. The write () function writes the num character from the buffer referred to by the Buf to the calling stream. The streamsize is a type defined by the C ++ library-it is a type, it can store the maximum number of characters that can be converted by any I/O operation.
39. streamsize gcount ();
Check how many characters have been read
40. Get:
Istream & get (char * Buf, streamsize num );
Read the character into the array directed by the Buf until the num-1 character is read and a line break or the end of the file is found. The array to which the pointer Buf points ends with a null character.
Istream & get (char * Buf, streamsize num, char delim );
Read the character into the array directed by the Buf until the num-1 character is read, and the character specified by the delim or the end of the file is found. The array to which the pointer Buf points ends with a null character. If a separator character is encountered in the input stream, the character is not extracted.
Int get ();
Returns the next character of the corresponding stream. If the end of the file is reached, the EOF is returned. The get () function is similar to the C function.
41. istream & Getline (char * Buf, streamsize num );
Read the character into the array directed by the Buf until the num-1 character is read and a line break or the end of the file is found. The array to which the pointer Buf points ends with a null character. If the line break is encountered in the output input stream, this character is extracted, but it is not put into the Buf
Istream & Getline (char * Buf, streamsize num, char delim );
Read the character into the array directed by the Buf until the num-1 character is read, and the character specified by the delim or the end of the file is found. The array to which the pointer Buf points ends with a null character. If a separator character is encountered in the input stream, this character is extracted, but it is not put into the Buf
42. bool EOF ();
When the end of the file is reached, this function returns true; otherwise, false.
43. istream & ignore (streamsize num = 1, int_type delim = EOF );
This function reads and waives characters until num characters are ignored (1 by default) or if delim is specified as a character (EOF by default)
44. int_type PEEK ();
Returns the next character in the stream. If the end of the file is reached, the EOF (int_type is defined as an integer type) is returned)
45. istream & putback (char C );
Returns the last character in the stream. c is the last character to read.
46. ostream & flush ();
Forcibly write data to the disk before the buffer zone is full
47. istream & seekg (off_type offset, seekdir origin );
Ostream & seekp (off_type offset, seekdir origin );
Off_type is an integer type defined by ios. It can contain the maximum valid values of offset. seekdir is an enumeration type defined by IOS and is used to determine the search method. The seekg () function can offset the current get pointer of the relevant file from the specified origin. The origin must be one of the three values.
IOS: Beg File Header
IOS: current location of cur
IOS: End file tail
The seekp () function can offset the current get pointer of the relevant file from the specified origin. The origin must be one of the three values.
48. pos_type tellg ();
Pos_type tellp ();
Determine the position of each file pointer. Pos_type is the type defined by IOs, and its storage function can return the maximum value.
I/O status: it is saved in an iostate object, which is an enumeration type defined by IOs, including the following members:
IOS: goodbit no error bit setting
IOS: eofbit: 1 at the end of a file; otherwise, 0
IOS: failbit: When a non-fatal error occurs, the value is 1. Otherwise, the value is 0.
IOS: badbit: 1 when a fatal I/O error occurs; otherwise, 0
How to obtain the I/O-like body:
A. iostate rdstate ();
B. bool bad ();
Bool EOF ();
Bool fail ();
Bool good ();
Once an error occurs, you may need to clear the error before the program continues to run. Therefore, you can use the clear () function.
Void clear (iostate flags = IOs: goodbit );
Reference: C ++ reference (version 4)
End of this Article
Reprinted to indicate the source. Thank you.
2010-08-19