ptg10805159
156 StandardI/O Library Chapter 5
library is not much slower than calling thereadandwritefunctions directly.For
most nontrivial applications, the largest amount of user CPU time is taken by the
application, not by the standardI/O routines.
5.9 BinaryI/O
The functions from Section 5.6 operated with one character at a time, and the functions
from Section 5.7 operated with one line at a time. If we’redoing binary I/O, we often
would like to read or write an entirestructure at a time. To do this usinggetcorputc,
we have to loop through the entirestructure, one byte at a time, reading or writing each
byte. Wecan’t use the line-at-a-time functions, sincefputsstops writing when it hits a
null byte, and theremight be null bytes within the structure. Similarly,fgetswon’t
work correctly on input if any of the data bytes arenulls or newlines. Therefore, the
following two functions areprovided for binary I/O.
#include <stdio.h>
size_t fread(void *restrictptr,size_tsize,size_tnobj,
FILE *restrictfp);
size_t fwrite(const void *restrictptr,size_tsize,size_tnobj,
FILE *restrictfp);
Both return: number of objects read or written
These functions have two common uses:
- Read or write a binary array.For example, to write elements 2 through 5 of a
floating-point array, we could write
float data[10];
if (fwrite(&data[2], sizeof(float), 4, fp) != 4)
err_sys("fwrite error");
Here, we specifysizeas the size of each element of the array andnobjas the
number of elements.
- Read or write a structure. For example, we could write
struct {
short count;
long total;
char name[NAMESIZE];
}item;
if (fwrite(&item, sizeof(item), 1, fp) != 1)
err_sys("fwrite error");
Here, we specifysizeas the size of structureandnobjas 1 (the number of objects
to write).