Structure hopping
Mike Stefanik/78125
mike at bria.AIX
Fri Jan 4 16:19:00 AEST 1991
In article <949 at tfsg.UUCP> mark at tfsg.UUCP (Mark Crafts) writes:
>Forgive my ignorance, but is there a quick 'n' simple way to say,
>dump a structure to a file (or whatever) using pointers, if we
>know that the structure only consists of, (for example) chars?
[proceeds to describe a structure]
Actually, there is a very simple way to do this; consider the following:
struct foo {
int anumber;
long along;
char somestring[64];
float areal;
char anotherstring[128];
} bar;
funwithfoo()
{
int fd;
/* here we open a file named "datafile"; this usage opens the
file for reading and writing, appending to the file if it
exits, otherwise creating it */
if ( (fd = open("datafile",O_RDWR|O_CREAT|O_APPEND,0644)) == -1 ) {
fprintf(stderr,"Bad karma dude! I cannot create datafile\n");
exit(1);
}
/* here we write the contents of 'bar' out to the file we just opened;
note the & operator that provides us with the address of 'bar',
which is sizeof(struct foo) bytes */
write(fd,&bar,sizeof(struct foo));
/* here we close our file */
close(fd);
/* now, let's reopen the file, and sequentially read through the
records that we have written (perhaps in the past?) */
if ( (fd = open("datafile",O_RDONLY)) == -1 ) {
fprintf(stderr,"Bad karma dude! Datafile doesn't exist!\n");
exit(1);
}
while ( read(fd,&bar,sizeof(struct foo)) == sizeof(struct foo) ) {
/* here we display the guts of struct foo */
};
close(fd);
}
Forgive any typos, etc. Hopefully you'll get the picture.
-----------------------------------------------------------------------------
Michael Stefanik, Systems Engineer (JOAT), Briareus Corporation
UUCP: ...!uunet!bria!mike
"If it was hard to code, it should be harder to use!"
More information about the Comp.lang.c
mailing list