Re: Structure size and binary format



gamehack wrote:

I've been wondering when I write a structure like:

struct {
  int          a;
  unsigned int b;
  float        c;
} mystruct;

And then I'm using this as a record for a binary file. The
problem is that the size of the types is different on different platforms(win/lin/osx) so if a file was copied on another
platform and attempted to be read then the first say 16 bytes
could be regarded as the integer a but it could have been
created on system where integer was 32 bytes.

Good. You recognize the existence of a problem. The answer is "Don't do that". Binary representations are, in general, not portable. You can convert things into a sequence of bytes and write/read those to a file, but that means you also have to write the conversion mechanisms. Now such things as byte sex can bite you.


Far and away the most portable transportation mechanism is pure text. You already have conversion routines in the standard library, and all you need to do is use them. Anybody and their dog can read the files.

--
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on
 "show options" at the top of the article, then click on the
 "Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
.



Relevant Pages

  • Re: Structure size and binary format
    ... And then I'm using this as a record for a binary file. ... but that means you also have to write the conversion mechanisms. ... Far and away the most portable transportation mechanism is pure text. ...
    (comp.lang.c)
  • Re: Very strange problem using FWRITE() to write data to a binary file
    ... > I'm facing a very very strange problem with a very very simple C ... > My goal should be to write to a binary file some numbers, ... > I made this stupid trial code: ... the broken "Reply" link at the bottom of the article. ...
    (comp.lang.c)
  • Re: Uploading Binary files to HTTPS
    ... doing something that causes the content to be terminated by the first zero ... e.g. handling a BSTR carelessly. ... I posted the code at the bottom.. ... binary file.. ...
    (microsoft.public.vc.language)