O'Reilly logo

UNIX Filesystems: Evolution, Design, and Implementation by Steve D. Pate

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>
2
3 main()
4 {
5          FILE    *fp;
6          char    c;
7
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);
13
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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required