C input buffer and redirection, C input buffer redirection
Input buffer:
First, let's look at a echo applet, which displays the characters entered by the user on the screen.
//echo.c
#include<stdio.h>int main(){ int ch; while((ch=getchar())!=EOF) { putchar(ch); }}
The running result is as follows (press ctrl + d to exit the loop and the program ends)
Another possible result of this program on different systems is:
Hheelloo
This is generally an exception. In most systems, nothing will happen before you press enter, as shown in the first result.
Input character immediate echoUnbuffered)OrDirect(Direct) is an instance of input, which indicates that the input character pairs are immediately available to the waiting program.
Conversely, the latency ECHO isBuffer(Buffered) Input instance. In this case, the characters entered are collected and stored in a temporary storage area called buffer, when you press enter, the entered character block becomes available for the program, so it is displayed on the screen together.
The role of the buffer zone:
1. It takes less time to transmit several characters as a block than to send these characters one by one
2. If the input is incorrect, you can use the delete key to modify it.
Applicability of non-buffered input: some interactive programs want to press the key to execute a command
There are two types of buffering:
Full buffer I/O: the buffer is cleared when it is full (the content is sent to another destination). This type of buffer is usually displayed in the file input.
Row buffer I/O: clears the buffer when a line break occurs. The keyboard uses the standard row buffer. Press the Enter key to clear the buffer.
Redirection:
By default, the C program of the standard I/O package uses the standard input as its input stream. This stream is created as a conventional method for reading data from a computer. Now it is generally our Keyboard. Similarly, the standard output stream is generally our monitor.
However, we can redirect a standard input/output stream to a file.
Now we use the mywords file (a file created randomly, some characters are entered) instead of the keyboard as our input using echo
Sure enough, the echo program displays the content in mywords.
<The symbols are Unix, Linux, and DOS.Redirection OperatorThis operator associates the mywords file with the standard input stream and directs the content of the file to the echo program.
Similarly, you can use the> symbol to redirect the output stream to a file.
We can see that the program outputs the string we input from the keyboard to myword, instead of going back to the screen.
Reference: C primer plus