(e-mail address removed) said:
-- foo.c --
#include <stdio.h>
int main(void) {
struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --
Is there any problem with the above snippet?
Add:
printf("[%d] [%d]\n", foo.a, foo.b);
after the fread, recompile, and test. Whilst this cannot prove that there
is not a problem with the snippet, it may be able to prove that there /is/
a problem.
I doubt very much whether you will get the results you desire!
In particular, with reading a struct with fread like that, instead of
reading each member seperately.
If it was written like that, it can be read like that on the same platform
(same compiler, same switch settings, yadayadayada). So you can do this:
#include <stdio.h>
#define TESTFILE "test.foo"
int main(void)
{
struct { int a; int b; } foo = { 6, 42 };
FILE *fpw = fopen(TESTFILE, "wb");
if(fpw != NULL)
{
int ok = 0;
printf("before write: foo.a = %d\nfoo.b = %d\n", foo.a, foo.b);
fwrite(&foo, 1, sizeof foo, fpw);
ok = !ferror(fpw);
fclose(fpw);
if(ok)
{
FILE *fpr = fopen(TESTFILE, "rb");
if(fpr != NULL)
{
foo.a = 10; foo.b = 20; /* any old junk, just to prove the point */
printf("after reset: foo.a = %d\nfoo.b = %d\n", foo.a, foo.b);
fread(&foo, 1, sizeof foo, fpr);
if(!ferror(fpr))
{
printf("after read: foo.a = %d\nfoo.b = %d\n", foo.a, foo.b);
}
fclose(fpr);
}
}
}
return 0;
}
This code has been (rather cursorily) tested, and a bug removed. One kudos
point available to whoever can work out what the bug was.