Linux C Learning-viewing streams and buffers from standard input and output

Source: Internet
Author: User
Tags stdin

To learn the standard input and output, we all encounter a concept, stream and buffer, but what exactly is a stream and what is a buffer?

The book "C Primer Plus" says that theC program handles a stream rather than processing the file directly. The explanation behind it is very abstract: "Stream"is an idealized stream of data that the actual input or output maps to this data stream. What is this flow specifically about?

The flow of this definition is very image. We can understand this:
You declare a file *FP, and assign the value returned by fopen (one of the files) to the FP two action is equivalent to setting up a faucet, when you use an input function such as GETC (FP) to read the file character is equivalent to unscrew the tap, For every character read, the file flows like water, and the address thatthe FP refers to is naturally moved backwards.

1 int ch; 2  3 while (CH=GETC (fp)! =EOF)4  5 putchar (CH);

You look at this loop and can read all the characters of a file. If it is not a stream,ch is always the first character and will not be updated. It can also be understood thatFP auto + + (the size of a character).

But what does the concept of flow mean?
--flow is a logical means of manipulating peripherals independent of the device.
-Most peripherals are different, so they require specialized programming techniques.
--The stream hides these differences from the programmer and allows them to handle most peripherals in the same way.
--given that a string of characters needs to be read one at a time, the stream (equivalent) is an interface with buffering effect.
--personal computers are based on streaming architecture.

There are some inconsistencies in the convection of the major authorities, and I think the stream is both an abstraction of the source or destination of the data and a representation of the flow of information between source and destination. But the flow at least implies the following aspects:
1, flow is an abstract concept, is an expression of information; In a program, a flow is an abstraction of an object's input and output information. Just like a transport tool is an abstraction of all movement vectors.
2, Flow is a"Moving"The concept of stationary storage of information on media only when it is prepared in a certain sequence"Sports"is called a stream."Move in or out of bytes from a program"Is"Moving"The performance. The static information has the potential to flow, but not necessarily the flow, like a car without petrol can not walk, it has the potential of transport, but it is not a means of transport (because it is likely to be used as a house, I saw a smart businessman on the street to use the train car to make a bar).
3, the flow has the source also has the destination, the program each kind of movement information has its source and the goal, remembers the programming (especially the assembly), always must determine the good operation the source operation number and the goal operand. To borrow a Buddhist statement is also:"All things have cause and effect."This is like the Yangtze River, west from the Tang Gula, and east to the Pacific." A car that is racing on the highway must have its origin and destination.
4, flow must have some kind of information, there is no content flow with itself to express "empty " information. Just like the means of transport, it transports its own parts (including the driver) and transports one thing to its destination when it is not shipped, and it is itself and a " information. The flow has the smallest information unit is bits, contains the smallest packet is the byte, c standard library provides two types of streams: binary stream (binary stream) and text flow ( Span lang= "en-us" >text stream). A binary stream is a sequence of unprocessed bytes; a text stream is a sequence of lines of text. In the famous unix system, the text flow and the binary stream are the same (identical).
5, the stream has a source and destination, then it must be associated with the source and destination. However, when people operate the flow, the most concern is its destination, that is, a directional (orientation), just like the driver of goods, its primary concern is the destination, not the starting point (operators know). In the C language, by opening a stream to correlate the stream and its destination, the function used is fopen (), which returns a pointer to the file (
file is a struct (excerpt from tc2.0 stdio.h file)

1 /*Definition of the control structure for streams*/2typedefstruct  {3          ShortLevel/*fill/empty level of buffer*/4unsigned flags;/*File Status Flags*/5          CharFd/*File Descriptor*/6UnsignedCharHold/*Ungetc Char if no buffer*/7           ShortBsize;/*Buffer Size*/8UnsignedChar*buffer;/*Data Transfer Buffer*/9UnsignedChar*curp;/*Current Active pointer*/Tenunsigned istemp;/*Temporary file indicator*/ One           ShortToken/*used for validity checking*/ A} FILE;/*This is the FILE object*/

Calling it a flow control structure (control structure for streams) really shows its functionality. For example, as if a truck driver were to ship the goods to X company, the head of the company would give him a map and basic information about X company, which would be able to instruct the driver to deliver the goods accurately if enough information was provided. The structure of file in C acts as if it were a file bag in which the transport company encapsulates all useful guidance information. Just the associated stream. To terminate this association, the stream must be closed, and the function used is fclose (), as if the shipping company is no longer shipping x company, then they have to terminate the cooperation agreement.
It is important to note that stdin, stdout, and stderr are the logical purposes of the standard input stream, the standard output stream, and the standard fault stream respectively, and they all correspond to the corresponding physical terminal by default. At the beginning of the program, the open () operation is not required and the stream is automatically opened.

What does the buffer zone mean?

In order to match the speed of communication between the computer fast device and the slow device, the computer uses a lot of hardware buffers (such as cache in the CPU, memory relative to the hard disk and CPU), the flow is a logical representation of the transmitted information, and the various operations of the convection may also have the need to use buffering. But the buffer here is just a logical concept, not a physical device. The buffer exists between the stream and the specific device terminal or the file on the storage media. As if shipping to a company, the contract requirements are shipped to x company, but is it true that the goods are actually shipped to x company's headquarters building? No. should be shipped to X company's warehouse. The warehouse here is a bit like what we call the buffer zone. It can also be said that the flow of movement to the purpose, the first pass is the buffer.

Take scanf () printf () as an example:

? The buffer (stream) is responsible for establishing a connection between the input/output device and the program.

– Input device, memory buffer (stdin), program

– Output device, program--memory buffer (STDOUT)

? is a temporary storage area, or in memory, or on the device's control card

. The buffer type.

The standard library provides buffering to reduce calls to read and write. There are three types of buffers available (organized from APUE):

    • Fully buffered.

In this case, the actual I/O operation occurs only after the buffer is filled. The operation of a file residing on disk is generally a standard I/O library that provides full buffering. Buffers are typically assigned by the malloc function called by standard I/O functions when I/O operations are performed on the first stream.

The term flush describes the write operation for standard I/O buffers. Buffers can be automatically flushed by standard I/O functions (for example, when the buffer is full), or we call the Fflush function for convection.

    • Row buffers

In this case, the actual I/O operation is performed only when a line break is encountered in the input/output. This allows us to write one character at a time, but I/O is only done after a line has been written. In general, flows that involve the terminal-such as callout input (stdin) and standard output (STDOUT)-are line buffered.

    • No buffering

The standard I/O library does not cache characters. It is important to note that the standard library does not cache and does not imply that the operating system or device drivers do not cache.

Of course, our usual scanf () and printf () are row buffers, so let's look at an example that can help us understand the role of buffers in standard input and output:

1 #include <stdio.h>2  3int  main ()4{5 printf ("helloWorld"); 6  while (1); 7 }

Let's look at the output:

1 1 1 . C 2  3 [email protected]:~/qiang/char1$./1

Playing is an empty, why?

We mentioned above that the standard input and output is a row buffer, that is, a full line will be refreshed, then what is the refresh? Refresh is to take the data out of the buffer, really can refresh, to meet what conditions?

1, full refresh, that is, a line full (1024 bytes) will be refreshed;

2, encountered ' \ n ' will refresh;

3, call fflush () function;

4, the end of the program fclose ();

We can see the above program, should have while (1), the program has not ended, no ' \ n ', no full line, no fflush (), so it does not output;

That way, we can change it, write a bar, add ' \ n ':

1 #include <stdio.h>23int  main ()4{5 printf ("helloworld\n"); 6  while (1); 7 }

The results of the implementation are as follows:

1 1 1 . C 2 [email protected]:~/qiang/char1$./13HelloWorld4  

Linux C Learning-viewing streams and buffers from standard input and output

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: 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.