ptg10805159
Section 5.10 Positioning a Stream 157
The obvious generalization of these two cases is to read or write an array of structures.
To dothis,sizewould be thesizeofthe structure, andnobjwould be the number of
elements in the array.
Bothfreadandfwritereturn the number of objects read or written. For the read
case, this number can be less thannobj if an error occurs or if the end of file is
encountered. In this situation,ferrororfeofmust be called. For the write case, if
the return value is less than the requestednobj, an error has occurred.
Afundamental problem with binary I/O is that it can be used to read only data that
has been written on the same system. This was OK many years ago, when all the UNIX
systems werePDP-11s, but the norm today is to have heterogeneous systems connected
together with networks. It is common to want to write data on one system and process
it on another.These two functions won’t work, for two reasons.
- The offset of a member within a structurecan differ between compilers and
systems because of different alignment requirements. Indeed, some compilers
have an option allowing structures to be packed tightly, to save space with a
possible runtime performance penalty, or aligned accurately, to optimize
runtime access of each member.This means that even on a single system, the
binary layout of a structurecan differ,depending on compiler options. - The binary formats used to storemultibyte integers and floating-point values
differ among machine architectures.
We’ll touch on some of these issues when we discuss sockets in Chapter 16. The real
solution for exchanging binary data among different systems is to use an agreed-upon
canonical format. Refer to Section 8.2 of Rago[ 1993 ]or Section 5.18 of Stevens, Fenner,
&Rudoff[ 2004 ]for a description of some techniques various network protocols use to
exchange binary data.
We’ll return to thefreadfunction in Section 8.14 when we use it to read a binary
structure, the UNIX process accounting records.
5.10 Positioning a Stream
Thereare three ways to position a standardI/O stream:
- The two functionsftellandfseek.They have been around since Version 7,
but they assume that a file’s position can be stored in a long integer. - The two functionsftelloandfseeko.They wereintroduced in the Single
UNIX Specification to allow for file offsets that might not fit in a long integer.
They replace the long integer with theoff_tdata type. - The two functionsfgetposandfsetpos.They wereintroduced by ISO C.
They use an abstract data type,fpos_t,that records a file’s position. This data
type can be made as big as necessary to recordafile’s position.
When porting applications to non-UNIX systems, usefgetposandfsetpos.