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. What happens here is that
fwrite receives a pointer to the structure, and writes (or fread correspondingly
reads) the memory image of the structure as a stream of bytes. The sizeof operator
determines how many bytes the structure occupies.



(The call to fwrite above is correct under an ANSI compiler as long as a prototype
for fwrite is in scope, usually because <stdio.h> is #included.



However, data files written as memory images in this way will not be portable, particularly
if they contain floating-point fields or pointers. The memory layout of structures
is machine and compiler dependent. Different compilers may use different amounts
of padding , and the sizes and byte orders of fundamental types vary across machines.
Therefore, structures written as memory images cannot necessarily be read back in
by programs running on other machines (or even compiled by other compilers), and
this is an important concern if the data files you're writing will ever be
interchanged between machines.



Also, if the structure contains any pointers (char * strings, or pointers to other
data structures), only the pointer values will be written, and they are most unlikely
to be valid when read back in.

Posted by:Richards