-
How To Save Dynamic Data
Hi!
I have a big problem saving my dynamic data into a binary file.
This is my code:
Code:
// font structure
typedef struct _FONT_DATA
{
short Length, Height;
char Author[21], Email[31], Date[81], ID_CHAR[21], ID_FONT[11];
BYTE **Char;
} FONT_DATA;
FONT_DATA *FontData;
.
.
.
// this is the way I use to save my font data, for which I think is wrong
fwrite (FontData, sizeof (FONT_DATA), 1, FNTFile);
The result is that the only thing that gets saved is that static data (author, length, height, email, ...), the dynamic data is not saved at all. What to do??
-
fwrite performs a bitwise copy of a structure, this includes padding and pointer addresses, but it doesn't dereference pointers to get at the real data. The end result is that you have a worthless address in your file and your data is lost.
>What to do??
You have to work harder. For example, write the size in bytes of the dynamic data so that you know how much to read back later and then save the data that your pointers point to. You can't use a single fwrite, but you should avoid fread/fwrite anyway if you intend to write files with any portability at all. Unless you really really need the advantages of binary files, you would be better off writing each data member to a text file in a predefined format to ease reading. Otherwise you will still have to write each data member manually, only with proper binary operations you will end up doing more work than with text files.