Reading and Writing to/from a Stream

There are numerous stdio functions for reading and writing. This section describes some of the functions available and shows a different implementation of the cp program using various buffering options. The program shown below demonstrates the effects on the FILE structure by reading a single character using the getc() function:

1 #include <stdio.h>
3 main()
4 {
5          FILE    *fp;
6          char    c;
8          fp = fopen(“/etc/passwd”, “r”);
9          printf(“address of fp       = 0x%x\n”, fp);
10         printf(“  fp->_fileno       = 0x%x\n”, fp->_fileno);
11         printf(“  fp->_IO_buf_base  = 0x%x\n”, fp->_IO_buf_base);
12         printf(“  fp->_IO_read_ptr  = 0x%x\n”, fp->_IO_read_ptr);
14         c = getc(fp);
15         printf(“ fp->_IO_buf_base = 0x%x (size = %d)\n”,
16                fp->_IO_buf_base,
17                fp->_IO_buf_end fp->_IO_buf_base);
18         printf(“ fp->_IO_read_ptr = 0x%x\n”, fp->_IO_read_ptr);
19         c = getc(fp);
20         printf(“ fp->_IO_read_ptr = 0x%x\n”, fp->_IO_read_ptr);
21 }

Note as shown in the output below, the buffer is not allocated until the first I/O is initiated. The default size of the buffer allocated is 4KB. With successive calls to getc(), the read pointer is incremented to reference the next byte to read within the buffer. Figure 4.2 shows the steps that the stdio library goes through to read the data.

$ fpinfo
Address of fp    = 0x8049818
fp->_fileno      = 0x3
fp->_IO_buf_base = 0x0
fp->_IO_read_ptr = 0x0
fp->_IO_buf_base = 0x40019000 (size = 4096)
fp->_IO_read_ptr = 0x40019001
fp->_IO_read_ptr = 0x40019002

By running ...

Get UNIX Filesystems: Evolution, Design, and Implementation now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.