Richard Bos wrote:
> "Vladimir S. Oka" <> wrote:
>
> > bergko opined:
>
> > > typedef struct record{
> > >
> > > char *name
> > > int contact
> > > }rec;
> > >
> > > file1 = fopen(..,"wb");
> > > ..
> > > fwrite(rec, sizeof(rec),1,file1);
> > >
> > > I've tried the above but it doesn't seem to work properly. Could
> >
> > Of course it doesn't -- for various reasons. Most important one being
> > that your `rec` is type not a variable. If you used `sizeof` as a
> > function to shut up your compiler, you shouldn't have.
>
> More to the point, _it_ shouldn't have.
Yes, for the first mention of `rec`. Seeing OP had typed the code
without care to make it barely correct, I disregarded that bit.
> > Below is some code that demonstrates what you may want, but beware, it
> > has no error checking whatsoever, and makes some assumptions that may
> > not hold for you (e.g. that "testfile" is a valid file name). It does
> > compile cleanly, and runs as expected on my Linux box.
>
> > typedef struct record{
> > char *name;
> > int contact;
> > } rec ;
>
> > rec a_rec = {NULL, 42};
> > rec b_rec = {NULL, 24};
>
> > fwrite(&a_rec, sizeof a_rec, 1, file1);
>
> > fread(&b_rec, sizeof b_rec, 1, file1);
>
> Another, more important, catch is that this you can only expect to read
> back a valid pointer value if it was null to begin with, or if you are
> still running the same execution of the program and haven't deallocated
> the memory that the pointer pointed at.
> For example, writing a pointer to an automatically allocated array and
> then reading it back in another call of the same function may easily put
> that array in another place in memory, making the pointer invalid.
> Writing a pointer in one run of the program, and reading it back in
> another, is even more likely to do the same.
You are, of course, right. I managed to overlook (as in "saw but did
not see") the fact that one member is actually a pointer. It also
wasn't clear (to me) what exactly was OP's problem: getting it to
compile and run, or perform as expected (whatever it was that was
expected).
|