tags:

views:

183

answers:

1

The book Beginning Linux Programming (3rd ed) says

"Note that fread and fwrite are not recommended for use with structured data. Part of the problem is that files written with fwrite are potentially nonportable between different machines."

What does that mean exactly? What calls should I use if I want to write a portable structured data reader or writer? Direct system calls?

+2  A: 

The book is wisely cautioning against reading an block of bytes from a file directly into a data structure.

The problem with this is that there can be unnamed padding bytes between individual elements of a data structure, and the number and position of these bytes is entirely implementation dependent.

You can still use the fread and fwrite calls to read and write data from and to a file, but you should read and write each element of the data structure individually, rather than reading or writing the whole struct at once.

There are other portability concerns you'll want to keep in mind as well. For example, the various numeric types have implementation-dependent sizes. For portability, you can use the types defined in the stdint.h header.

There may also be differences in floating point and unsigned integer representation, but most systems and file formats now use IEEE 754 and two's-complement, respectively, so compatibility issues are far less frequent with those types. Just make sure you know what your specifications say.

James McNellis
Thank you very much. It seems to be none business of fread or fwrite,becasue as far as I know, data struture is always padded implementation-dependently.Is it wierd to stress this issue when talking about specific calls like fread or fwrite?
forest58
@forest: It's exactly *because* fread/fwrite don't know about padding that using them can fail. For example, given `struct A { int i; char c; };`, you need two fread calls (one for each of *i* and *c*) rather than one (for the whole struct). The point about portable integer types is so you don't depend on the specific number of bits used by `int` (which can vary by platform and even compiler settings).
Roger Pate