Input/Output stream Summary (reprint)

Source: Internet
Author: User
Tags fread setf

C + + supports two I/O, the first of which is inherited from the C language, and is an object-oriented I/O system defined by C + +.

1, int getchar (void), return an integer value, or specify the value as a char variable, because the character is contained in the low byte (the high byte is usually 0), and if there is an error, GetChar () returns EOF. But he has a potential problem, under normal circumstances, GetChar () cache input until you type the ENTER key (this should be a deep experience, that is, GetChar () seems to only know the ENTER key, which is the reason) this is called the row buffer input, A enter key must be typed before the character is actually delivered to the program.

2, int putchar (int c);

Although Putchar () takes an integer argument, it can usually be called with a variable of one character, but only its low byte is actually output to the screen, the Putchar () function puts back the characters written, and if the operation fails, returns EOF (the macro EOF is defined in stdio.h, usually with a value of-1 )。

3, int getch (void);

int Getche (void);

Two most commonly used interactive functions, for most compilers, prototypes of these functions can be found in the header file Conio.h, which are underlined in front of some compilers. such as _getch () and _getche (); This is why in VS2008 often prompted to add a ' _ ' in front.

4, char* gets (char* str);

Reads a string entered from the keyboard and stores it in an address referred to by another variable, which reads characters from the keyboard until the ENTER key is encountered. The Enter does not enter a part of the string, instead the null terminator is placed at the end of the string and returned by the Get (). However, using get () is careful because it does not perform bounds checking on the character array that is being accepted for input. Therefore, the user can type more characters than the array can hold. Although it is good for the sample programs and simple tools you use, it is not generally used in commercial code. The alternative to it is fgets (), which is described later.

5, int puts (const char* str);

Writes its string element to the screen, followed by a new line. It is called more than printf () and is less expensive because puts () can only input strings, cannot output numbers or format conversions, so puts () uses less space and is faster than printf (). Thus the function puts () is often used for code optimization, 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 characters written, and if an error occurs, the return control_string (control string) consists of two types of items. The first class consists of a string that will be printed on the screen, and the second class includes a format qualifier that customizes the display of subsequent arguments. The format qualifier begins with a percent symbol followed by a format code, and the number of elements in the list of elements is exactly equal to the format qualifier, and the format qualifier matches the variable in order from left to right.

7, int scanf (const char* control_string ...);

You can read into various inline types and automatically convert them to the appropriate format. Returns the data item that was successfully assigned a value. If an error occurs, scanf () returns EOF. The control string consists of three types of characters:

A, Format qualifier B, white space character C, non-whitespace character

The format qualifier starts with a percent sign and tells SCANF () what type of data to read Next.

8. file* fopen (const char*filename,const*char* mode)

Open a file

The mode legal value is as follows:

R opens a text file for the read operation

W Create a text file for the write operation

A attached to a text file

RB opens a binary file for read operations

WB creates a binary file for write operations

AB attached to a binary file

r+ opening a text file for read/write operations

w+ Creating a text file for read/write operations

A + attach or create a text file for a read/write operation

R+b opening a binary file for read/write operations

W+b creating a binary file for read/write operations

A+b attaching a binary file to a read/write operation

If the file fails to open, fopen () returns a null pointer.

9, int fclose (file* fp);

Closes a file opened by fopen (), writes the data left in the disk buffer to the file, and formally closes the file at the operating system level. Failure to close a stream file can cause a variety of problems, such as losing data, destroying intermittent errors in files and programs, and so on. Flose () also releases the control block with the stream file so that it can be reused.  Sometimes, because the operating system has a limited number of files open at a time, you must close one file before you open another file. Return 0 marks the successful closing of the file. If the shutdown fails, the EOF is returned. The standard function ferror () can be used to determine and report error messages. Typically, fclose () is removed prematurely in the drive in disk or there is no more space on the disk for the wrong times.

10, int putc (int ch,file* fp);

Writes a character to the file, and if the operation succeeds, the function returns the bytes that were output, otherwise, returns EOF

11, int getc (file* fp);

Reads a character from a file, the function getc () returns the EOF flag when the end of the file is read, and EOF if an error occurs.

12, Fgetc (), with GETC ()

13, int fgets (const char*str,int length,file* FP); reads a string from a file until a newline character is read or length-1 characters are read, and if a new line is read, it is part of the original string (unlike get () As a new string), the resulting 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 that str points to the specified stream and, if it fails, returns EOF

15, Fseek (), find a specific byte in the file

16, Ftell (), returns the location of the current file

17, fprintf (), output to disk file

18, FSCANF (), read data from disk

19, int feof (file* fp);

Returns the true value if it is at the end of the file. Can be used for binary files or for text files

eg

while (!feof (fp)) ch = getc (FP);

20, int ferror (file* fp);

function to determine whether an error occurred during a file operation. The FP is a valid file pointer. The function returns True if there is an error during the file operation, otherwise false is returned. Because each file operation sets an error condition, you should call Ferror () immediately after the action in each file, or you will lose the error message.

21, Void Rewind (file* fp), the file position pointer back to the beginning of the file, FP is a valid file pointer,

22, int remove (const char*filename), clears a file, the operation succeeds, returns 0, and the operation fails to return a non-0 value.

23, int fflush (file* fp);

Clears the contents of an output stream, writes the contents of any buffer to the FP-related file, and if Fflush () is called when the FP is empty, all open files for the output are emptied. The operation returned 0 successfully, otherwise EOF is returned.

24,size_t fread (void* buffer,size_t num_byte,size_t count,file* fp);

Buffer is a pointer to a store that receives data from a file, and the value of count indicates how many items to write. Returns the number of entries read, such as the end of the file or the operation failed. 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 to the information that you want to write to the file quickly. The value of count indicates how many entries to write. Returns the number of entries written, which is always equal to count, unless the operation fails.

Note: The size_t type is defined as an unsigned integer, and the FP is a pointer to a file that has already opened the stream. One of the biggest uses of fwrite () and Fread () is the ability to write user-defined data types, especially struct types

26, int fseek (file* fp,long int numbytes,int origin);

The FP is a pointer returned by fopen (), NumBytes is the byte from the origin location of the file to the current position, and is one of the following macros:

Origin Macro Name

File starts at Seek_set

Current position Seek_cur

End of File Seek_end

You can use Fseek () to find multiples of any data type by multiplying the number of items you want 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, returning the address of the current location of the file associated with the FP. If it fails, return-1.

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 ways to read and write data from disk files, they are not the most efficient method. Because formatted Ascⅱ data is written to the same format as it would appear on the screen (not in binary mode), it is called with additional overhead. If you want to consider speed and file length, it's best to use Fread () and fwrite ()

C + + built-in streams

Stream meaning Default device

CIN Standard Input Keyboard

cout Standard Output screen

Cerr standard Error Output screen

Clog Cerr's buffered version screen

The stdin, stdout, and stderr of Cin, cout, Cerr and C correspond.

C + + additional streams: Win, Wout, Werr, wlog they are all standard streams of character versions, with a wide character type of wchar_t, typically 16 bits.

29, Fmtflags SETF (fmtflags flags);

The function returns those tokens that were previously specified by the format tag and opened with flags.

eg

COUT.SETF (Ios::showpoint);

COUT.SETF (Ios::showpos);

or COUT.SETF (Ios::showpoint | ios::showpos);

30, void UNSETF (Fmtflags flags);

Flags the specified flags are cleared

eg

COUT.SETF (Ios::uppercase | ios::scientfic);

COUT.UNSETF (ios::uppercase);

31, Fmtflags flags ();

Returns the current position of each format marker.

32, Fmtflags flags (fmtflags f);

Sets all the tags for 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 field width, W is the field width to be changed, and the previous field width is returned.

34, Streamsize Precision (streamsize p);

When you output a floating-point type, you can use the precision () function to determine the exact number of digits.

35, Char Fill (char ch);

Fills the specified character, which by default is a space

C + + operator operators

operator use input/output

Boolapha Open Boolapha marker input/output

Dec on Dec flag output

Endl outputs a newline character and refreshes the stream output.

Ends output a null output

Fixed open fixed mark output

Flush refreshes a stream output

Hex turn on hex mark output/input

Internal turn on internal marker output

Left to turn on left marker output

Noboolalpha off Noboolalpha marker input/output

Noshowbase closing showbase marker output

Noshowpoint closing showpoint marker output

Noshowpos closing Showpos marker output

NOSKIPWS closing SKIPWS Tag input

Nounitbuf closing unitbuf marker output

Nouppercase closing uppercase marker output

Oct Open Oct Tag input/output

Resetiosflags (Fmtflags f) Close the marked input/output specified in F

Right to turn on the right marker output

Scientific turn on scientific marker output

SetBase (int base) sets the cardinality to base input/output

Setfill (int ch) sets the fill character to ch output

Setiosflags (Fmtflags f) Opens the labeled input/output specified in F

setprecision (int p) Set character precision output

SETW (int w) sets the field width to W output

Showbase turn on showbase marker output

Showpoint turn on showpoint marker output

Showpos turn on Showpos marker output

SKIPWS turn on SKIPWS marker input

Unitbuf turn on unitbuf marker output

Uppercase turn on uppercase marker output

WS Skip Start space input

Note: In accessing the operator with parameters, the <iomanip> must be included in the program

To create your own insert:

ostream& operator<< (ostream& stream,class_type obj)

{

Body of Inserter

return stream;

}

To create your own collection of filters

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 all content that is output to the appropriate file is added to the end of the file, which can only be used for files with output functionality.

Ios::ate allows you to navigate to the end of the file when you open the file

Ios::binary can be opened as a binary file, and all files are opened as text by default.

Ios::in specified as input

Ios::out Set My output

Ios::trunc destroys the contents of a previous file with the same name and truncates the file length to 0, and any previously existing files with that file name will be automatically truncated when an output stream is created using Ofstream

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 the NUM characters from the stream and puts them into a buffer referred to by BUF. The write () function writes the NUM character from a buffer referred to by BUF to the calling stream, Streamsize is a type defined by the C + + library--a type that stores the maximum number of characters that can be converted by any one I/O operation.

39, Streamsize Gcount ();

Check how many characters have been read

40. Overloaded version of Get ():

istream& get (char* buf,streamsize num);

Reads a character into an array that is pointed to by BUF until it reads to the num-1 character, finds a line break, or encounters a file end. The array pointed to by the pointer buf ends with a null character.

istream& Get (char* buf,streamsize Num,char Delim);

Reads a character into an array pointed to by BUF until it reads to the num-1 character, discovers the character specified by Delim, or encounters the end of the file. The array pointed to by the pointer buf ends with a null character. If a delimiter character is encountered in the input stream, the character is not extracted.

int get ();

Returns the next character of the corresponding stream, or EOF if the end of the file is encountered. This form of the Get () function is similar to the C function

41, istream& getline (char* buf,streamsize num);

Reads a character into an array that is pointed to by BUF until it reads to the num-1 character, finds a line break, or encounters a file end. The array pointed to by the pointer buf ends with a null character. If a newline character is encountered in the out input stream, the character is extracted, but it is not placed in the BUF

istream& getline (char* buf,streamsize Num,char Delim);

Reads a character into an array pointed to by BUF until it reads to the num-1 character, discovers the character specified by Delim, or encounters the end of the file. The array pointed to by the pointer buf ends with a null character. If a delimiter character is encountered in the input stream, the character is extracted, but it is not placed in the BUF

42, BOOL EOF ();

The function returns True when the end of the file is reached, otherwise false is returned

43, IStream & Ignore (streamsize num = 1,int_type Delim = EOF);

The function reads and discards characters until Num characters are ignored (the default value is 1) or Delim is specified as a character (default is EOF)

44, Int_type Peek ();

Returns the next character in the stream, or EOF if the end of the file is encountered (Int_type is defined as an integer type)

45, istream& putback (char c);

Returns the last character in the stream, and C is the last character read

46, ostream& Flush ();

Force data to be written to disk before the buffer is filled with data

47, istream& SEEKG (Off_type offset,seekdir origin);

ostream& SEEKP (Off_type offset,seekdir origin);

Off_type is an integer type defined by iOS that can contain the maximum valid value that offset has, and Seekdir is an iOS-defined enumeration type used to determine how to find. The SEEKG () function can shift the current fetch pointer of the relevant file from the specified origin to offset characters, and origin must be one of three values

Ios::beg file Header

Ios::cur Current Location

Ios::end file Footer

The SEEKP () function can shift the current fetch pointer of the relevant file from the specified origin to offset characters, and origin must be one of the above three values

48, Pos_type Tellg ();

Pos_type TELLP ();

Determines the location of each file pointer. Pos_type is an iOS-defined type that stores functions that can return the maximum value.

I/O Status: Keep an object of type Iostate, which is an enumeration type defined by iOS, including members:

Ios::goodbit no error bit setting

Ios::eofbit 1 When the end of the file is encountered; otherwise 0

Ios::failbit 1 If a non-fatal error occurs, otherwise 0

Ios::badbit 1 when a fatal I/O error occurs; otherwise 0

Methods for obtaining the I/O-shaped 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, so you can use the clear () function

void Clear (Iostate flags = ios::goodbit);

Input/Output stream Summary (reprint)

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.