Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!bria!mike From: mike@bria.AIX (Mike Stefanik/78125) Newsgroups: comp.lang.c Subject: Re: Structure hopping Message-ID: <315@bria.AIX> Date: 4 Jan 91 05:19:00 GMT References: <949@tfsg.UUCP> Reply-To: mike@bria.UUCP (Michael Stefanik) Organization: Briareus Corporation, Los Angeles, CA Lines: 60 In article <949@tfsg.UUCP> mark@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!"