In UNIX systems, the standard I/O Library eventually calls the file I/O (read, write, etc ). Each standard I/O Stream has a file descriptor associated with it. You can call the fileno function on a stream to obtain its descriptor.
Note that fileno is not an iso c standard, but an extension supported by POSIX.1.
#include <stdio.h> fileno( FILE *
This function is required if you want to call functions such as dup or fcntl.
To understand the implementation of the standard I/O Library in your system, it is best to start from the first file <stdio. h>. We can see how the FILE object is defined, how each stream flag is defined, and various standard I/O routines (such as getc) defined as macros ).
In program 5-3, the program prints buffer status information for three standard streams and the stream associated with a common file.
Program list 5-3 prints buffer status information for each standard I/O Stream
[root@localhost apue]# cat prog5- pr_stdio( *, FILE **( getchar() ==(( fp = fopen(, )) ==(getc(fp) == *name, FILE * (fp->_IO_file_flags & (fp->_IO_file_flags & , fp->_IO_buf_end - fp->
Note: before printing the buffer status information, perform an I/O operation on each stream. The first I/O operation usually causes a buffer to be allocated to the stream. The structure member _ IO_file_flags, _ IO_buf_base, _ IO_buf_end, constant _ IO_UNBUFFERED, and _ IO_LINE_BUFFERED are defined by the GNU standard I/O Library in Linux. It should be noted that other UNIX systems may have different standard I/O Library implementations.
If the programs in listing 5-3 run twice, connect the three standard streams to the terminal at one time, and redirect them to a common file at the other time, the result is:
[root@localhost apue]# ./prog5-= stdin, line buffered, buffer size = = stdout, line buffered, buffer size = = stderr, unbuffered, buffer size = = /etc/mtab, fully buffered, buffer size = /prog5- < /etc/termcap > std. >= stdin, fully buffered, buffer size = = stdout, fully buffered, buffer size = = stderr, unbuffered, buffer size = = /etc/mtab, fully buffered, buffer size =
It can be seen that the default situation of the system is: when the standard input and output are connected to the terminal, they are row buffering. The row buffer length is 4096 bytes. Note that this does not limit the length of input and output to 4096 bytes, which is only the length of the buffer. If you want to write 8192 bytes of rows to the standard output, you need to perform two write system calls. When these two streams are redirected to a common file, they become fully buffered, the buffer length is the preferred I/O length of the file system (the st_blksize value obtained from the stat structure ). We can also see that standard errors are not buffered as they should be, while normal files are fully buffered by default.