C ++ programming's understanding of the buffer zone

Source: Internet
Author: User

This is an article reprintedArticle, Slightly modified. The original text link is here.

What is a buffer?

A buffer is also called a cache, which is a part of the memory space. That is to say, a certain amount of storage space is reserved in the memory space, which is used to buffer input or output data. This reserved space is called a buffer zone. The buffer zone is divided into the input buffer zone and the output buffer zone based on whether it is an input device or an output device.

Why introduce a buffer?

Why should we introduce the buffer?

For example, if we retrieve information from a disk, we first put the read data in the buffer zone, and then the computer directly retrieves data from the buffer zone, and then reads the data from the disk after the buffer zone is obtained, in this way, the number of reads and writes to the disk can be reduced. In addition, the computer's operations on the buffer zone are much faster than those on the disk. Therefore, the application buffer can greatly improve the computer's operation speed.

For another example, we use a printer to print documents. Because the printer printing speed is relatively slow, we first output the documents to the corresponding buffer zone of the printer, and then print them gradually, at this time, our CPU can handle other things. Now, you basically understand that the buffer zone is a memory zone, which is used to cache data between the input and output devices and the CPU. It allows low-speed input/output devices and high-speed CPUs to coordinate work, avoiding low-speed input/output devices occupying CPU, freeing them from CPU, and enabling them to work efficiently.

Buffer type

There are three buffer types: Full buffer, row buffer, and no buffer.

1. Full Buffer

In this case, the actual I/O operation is performed only after the standard I/O cache is filled. A typical example of full buffer is read/write of disk files.

2. Row Buffering

In this case, when a line break is encountered in the input and output, the real I/O operation is executed. At this time, the entered characters are first stored in the buffer, and the actual I/O operation is performed only when the Enter key is changed. A typical example is keyboard input data.

3. No Buffer

That is, stderr is a typical example of standard errors, which allows error information to be displayed as soon as possible.
Refresh the buffer

In the following cases, the buffer is refreshed:

1. When the buffer is full;

2. Execute the flush statement;

3. Execute the Endl statement;

4. close the file.

It can be seen that when the buffer is full or the file is closed, the buffer is refreshed for real I/O operations. In addition, in C ++, we can use the flush function to refresh the buffer (execute the I/O operation and clear the buffer), such as cout <flush; // output the video content to the display immediately.

The Endl controller moves the cursor to the beginning of the next line of the output device and clears the buffer zone.

Cout <Endl;

Equivalent

Cout <"\ n" <flush;

Demo by instance

1. File Operation demonstration full Buffer

Create a console project, enter the followingCode:

# Include <fstream> Using   Namespace  STD; Int  Main (){  //  Create and open the test.txt file. Ofstream OUTFILE ( "  Test.txt  "  );  //  Write 4096 characters 'A' to the test.txt File'      For ( Int N = 0 ; N < 4096 ; N ++ ) {OUTFILE < '  A  '  ;}  //  Pause. Press any key to continue. System ( "  Pause  "  );  //  Write the 'B' character to the test.txt file, that is, the 4,097th character is 'B' OUTFILE < '  B  '  ; //  Pause. Press any key to continue. System ( "  Pause  "  );  Return   0  ;} 

The above code is easy to understand and has been commented out in the Code.

The purpose of writing this small code is to verify that the buffer size in Windows XP is 4096 bytes. After the buffer is full, the buffer is refreshed and the real I/O operation is performed.

Compile and execute the command. The running result is as follows:

When you open the test.txt file under the project folder, you will find that the file is empty. This indicates that the 4096 character "a" is still in the buffer zone and the I/O operation is not actually performed. Press enter. The window is changed to the following:

Then open the test.txt file, and you will see that the file already contains 4096 characters "". This indicates that the size of the full buffer zone is 4 K (4096). When the buffer zone is full, I/O operations are performed, and the character "B" is still in the buffer zone.
Press enter again and the window is changed to the following:

Then open the test.txt file, and you will find the character "B" in it. This step verifies that the buffer is refreshed when the file is closed.

To verify that the full buffer size is 4 K (4096 ),ProgramChanged:

# Include <fstream> Using   Namespace  STD;  Int  Main () {ofstream OUTFILE (  "  Test.txt  "  );  For ( Int N = 0 ; N < 4096 * 2 ; N ++ ) {OUTFILE < '  A  '  ;} System (  "  Pause  "  ); OUTFILE < '  B  '  ; System (  "  Pause "  );  Return   0  ;} 

Compile and execute the command. The running result is as follows:

Test.txt already has 4096 A, as shown below:

Press Enter:

Then, test.txt added 4096 a records, a total of 8 K.

Continue to pressEnter key,Test.txt adds B again. It can be seen that the full buffer size is indeed 4 K.

2. keyboard operation demonstration row Buffering

First, we will introduce the getchar () function.

Function prototype: int getchar (void );

Note: When the program calls the getchar () function, the program waits for the user to press the key and the characters entered by the user are stored in the keyboard buffer, until you press enter (the carriage return character is also placed in the buffer ). After you press enter, the getchar () function starts to read one character each time from the keyboard buffer. That is to say, subsequent getchar () function calls will not wait for the user to press the key, but directly read the characters in the buffer until the characters in the buffer are read, and then wait for the user to press the key again.

I don't know if you understand it. In other words, when the program calls the getchar () function, the program waits for the user to press the key and waits for the user to press the return key. The characters pressed during this period are stored in the buffer zone. The first character is used as the return value of the function. To continue calling the getchar () function, you will not wait for the user to press the button, but will return the 2nd characters you just entered. To continue calling the function, 3rd characters will be returned until the characters in the buffer zone are read, wait for the user to press the button.

If you do not understand it yet, you can only complain that my expression capability is limited.

Create a console project and enter the following code:

# Include <iostream> Using   Namespace  STD;  Int  Main (){  Char  C;  //  The first call to the getchar () function  //  During program execution, you can enter a string of characters and press the Enter key. This function is returned only after you press the Enter key. C =Getchar ();  //  Display the return value of the getchar () function Cout <C < Endl;  //  Pause System ( "  Pause  "  );  //  Call the getchar () function multiple times in a loop  //  Display the returned values of each call to the getchar () function.  // It will not end until it encounters a carriage return.      While (C = getchar ())! = '  \ N  '  ) {Printf (  "  % C  "  , C );}  //  Pause System ( "  Pause  "  ); Return   0  ;} 

This small code is also very simple, and there are comments inside the code.

The execution of the getchar () function uses row buffering. When you call the getchar () function for the first time, the program user (User) is asked to enter a line of characters until the return key function is pressed. The characters and carriage return characters entered by the user are stored in the row buffer zone.

Call the getchar () function again to gradually output the content of the row buffer.

Well, I have limited ability to express myself. Compile and run the program and understand it through the running results.

Compile and run the program, and you will be prompted to enter characters. you can press the following characters alternately:

When you press down, you will find that when you press to 4,094th characters, you are not allowed to continue to enter characters. This indicates that the row buffer size is also 4 K.

Press the Enter key to return the first character 'a', for example:

Continue to press the Enter key to output all other characters in the buffer zone, for example:

3. Standard Error output without buffering

If error output is used:

Cerr <"error. Check the input parameters !";

This statement is equivalent:

Fprintf (stderr, "error. Please check the input parameters !");

Well, let's talk about it. Good luck and hope it will help you.

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.