delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/07/12/19:03:16

From: "A. Sinan Unur" <asu1 AT cornell DOT edu>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: My structures get broken when I fwrite
Date: Sat, 12 Jul 1997 11:06:12 -0400
Organization: Cornell University http://www.cornell.edu
Lines: 53
Sender: asu1 AT cornell DOT edu (Verified)
Message-ID: <33C79D64.3A57@cornell.edu>
References: <33C76A7A DOT 15E4 AT swipnet DOT se>
Reply-To: asu1 AT cornell DOT edu
NNTP-Posting-Host: cu-dialup-0048.cit.cornell.edu
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Deltaman wrote:

it is in general not a good idea to save aggregate data types on disk.
the layout can change from one version of the compiler to the other in
addition to from one compiler to the other. your specific problem is
different though.
> 
> void save_board (map *b, char *fname)
>         {
>                 FILE *f;
> 
>                 f = fopen (fname, "wb");
> 
>                 fwrite (b->data, sizeof (my_struct), mapx * mapy, f);
>                 fclose (f);
>         }
> 
> void read_board (map *b, char *fname)
>         {
>                 FILE *f;
> 
>                 f = fopen (fname, "r");
> 
>                 fwrite (b->data, sizeof (my_struct), mapx * mapy, f);

you are opening the file in "text" mode. in addition you are writing to
it, not reading from it.

oh, what wonders cut&paste can do.

>                 fclose (f);
>         }
> 
> I know the data is correct before saving it, so I guess something in
> these functions must be wrong. Can any kind soul please help me. TIA!

in general, you should save your structures byte-by-byte and read them
in byte by byte forming the fields in the process if you want to be able
to read them using the same program on a variety of platforms (including
different versions of the same compiler.) compilers are free to change
the layout of the structure in memory as it suits their optimization
needs.
-- 
   Sinan
 
*******************************************************************
 A. Sinan Unur                                WWWWWW
                                              |--O+O
 mailto:sinan DOT unur AT cornell DOT edu                C   ^ 
 http://www.people.cornell.edu/pages/asu1/     \  ~/ 

Unsolicited e-mail is _not_ welcome, and will be billed for.
*******************************************************************

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019