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