IT Placement Papers Programming C
This category contains C Interview Questions and Answers |
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 .
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 fopening the files;
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.
Only registered users can write comments. Please login or register.
|