home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / std / c / 3010 < prev    next >
Encoding:
Text File  |  1992-11-15  |  2.2 KB  |  59 lines

  1. Path: sparky!uunet!munnari.oz.au!goanna!ok
  2. From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe)
  3. Newsgroups: comp.std.c
  4. Subject: Re: fwrite+fread of pointer
  5. Message-ID: <15977@goanna.cs.rmit.oz.au>
  6. Date: 16 Nov 92 09:42:07 GMT
  7. References: <15935@goanna.cs.rmit.oz.au> <1992Nov13.184421.11065@taumet.com>
  8. Organization: Comp Sci, RMIT, Melbourne, Australia
  9. Lines: 48
  10.  
  11. In article <1992Nov13.184421.11065@taumet.com>, steve@taumet.com (Steve Clamage) writes:
  12. : ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
  13. : >I would like to know what the standard says about the following program:
  14. : [ writes the contents of a pointer with fwrite, reads it back with fread ]
  15. : [ that is, whether the value read == the value written ]
  16. : ANSI C Standard 4.9.2:
  17. : "Data read in from a binary stream shall compare equal to the data that
  18. : were earlier written out to the stream, under the same implementation."
  19. : In the example, the file was opened in binary mode, so this applies.
  20.  
  21. That is exactly the kind of answer I hoped for when I posted to comp.std.c.
  22. Thank you.  There remains, alas, one fine point of detail.  What does it
  23. _mean_ to say "COMPARE EQUAL to the data ..."?
  24.  
  25. Consider this example:
  26.  
  27.     static struct foo {char a, b;} x, y = {2,3};
  28.     fwrite(&x, sizeof x, 1, f);
  29.     rewind(f);
  30.     fread(&y, sizeof y, 1, f);
  31.  
  32. In this case, it is not possible to ask the question x == y because
  33. == is not defined on structs.  So "compare equal" cannot refer to ==
  34. but must refer to something like memcmp().  But I always did accept that
  35.  
  36.     char dummy;
  37.     char *p = &dummy;
  38.     char block[sizeof p];
  39.  
  40.     memcpy(block, &p, sizeof p);
  41.     fwrite(&p, sizeof p, 1, f);
  42.     rewind(f);
  43.     fread(&p, sizeof p, 1, f);
  44.  
  45. must yield a state in which
  46.  
  47.     memcmp(block, &p, sizeof p) ==> 0
  48.  
  49. The question is whether the fact that the current value of p has the
  50. same _bytes_ that it used to have means that it is necessarily the
  51. same _pointer_.  The thing is, the wide licence allowed to casts has
  52. taught me to be very cautious about assuming much when pointers and
  53. bits are involved.  I know that casts are conversions, not merely type
  54. relabellings, and that fwrite() and fread() do not involve casts.  I
  55. mention casts only to explain why I am perhaps excessively wary.
  56.