### Question 2.11

How can I read/write structures from/to data files?

It is relatively straightforward to write a structure out using `fwrite`:

    	fwrite(&somestruct, sizeof somestruct, 1, fp);

and a corresponding `fread` invocation can read it back in. (Under pre-ANSI C, a `(char *)` cast on the first argument is required. What's important is that `fwrite` receive a byte pointer, not a structure pointer.) However, data files so written will not be portable (see questions 2.12 and 20.5). Note also that if the structure contains any pointers, only the pointer values will be written, and they are most unlikely to be valid when read back in. Finally, note that for widespread portability you must use the `"b"` flag when `fopen`ing the files; see question 12.38.

A more portable solution, though it's a bit more work initially, is to write a pair of functions for writing and reading a structure, field-by-field, in a portable (perhaps even human-readable) way.

References: H&S Sec. 15.13 p. 381

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback