home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ogicse!usenet.coe.montana.edu!rpi!gatech!usenet.ins.cwru.edu!po.CWRU.Edu!rat
- From: rat@po.CWRU.Edu (Reza A. Tabib-Azar)
- Newsgroups: comp.lang.c
- Subject: Re: ** HELP WITH FILE I/O **
- Message-ID: <1i7boaINNbku@usenet.INS.CWRU.Edu>
- Date: 3 Jan 93 18:36:58 GMT
- Article-I.D.: usenet.1i7boaINNbku
- References: <JmeswB1w165w@tradent.wimsey.bc.ca>
- Reply-To: rat@po.CWRU.Edu (Reza A. Tabib-Azar)
- Organization: Case Western Reserve University, Cleveland, OH (USA)
- Lines: 58
- NNTP-Posting-Host: slc12.ins.cwru.edu
-
-
- In a previous article, lord@tradent.wimsey.bc.ca (Jason Cooper) says:
-
- >Eeek! I am writing a program to handle a local track meet and have to
- >input the participant records from a file. What I want to do is load
- >these into an array for quick and easy access. The array is right now of
- >undefined length, and its elements are structures (including each event,
- >it's heat, it's event, etc.). I've tried using:
- >
- >fread(meet[record], sizeof(struct meetstruct), 1, tfile)
- >
- >Where meet is the array, meetstruct is the structure the array is
- >composed of, and tfile is the track meet's file stream. I don't know
- >_what_ I'm doing wrong, but if somebody could correct this (oops, forgot
- >to mention, that's in a loop to go through records, I tried taking the
- >whole thing in one, but that didn't work either), then I'd appreciate
- >that VERY MUCH. If I could input the whole thing in one with fread or
- >something, that would be _WONDERFUL_. I'm using Borland C++, and would
- >like to understand _what_ I'm doing, so if you could explain it too, that
- >would be nice. If I have to limit the size of the array, that's doable
- >too.
-
-
- [Stuff deleted]
-
- You see, fread and frwite are used to read and write a block of data. For
-
- example, you can write your whole array to a file and read it in one call as
- well. Therefore, you do not need to put the fread call in a loop. The first
- argument of fread is pointer to an array. Here is an example to for you
- to see, it will write a block of data and the data will be read back in.
-
- typedef struct {
- int a;
- char b;
- } foo;
-
- main()
- {
- FILE *fp;
- foo inbuff[3];
- foo outbuff[3] = { {1, 'q'}, { 2, 'w'}, { 3, 'e'}};
-
- fp = fopen("myfoofile", "wb+");
- fwrite( outbuff, sizeof(foo), 3, fp);
- rewind( fp );
- fread( inbuff, sizeof(foo), 3, fp);
- /* do what ever you like to do with the inbuff array (no magic) */
- fclose(fp);
- }
-
- I hope this will clarify things a bit.
-
-
- --
- main() { printf("\t\tReza A. Tabib-Azar\b\n");
- printf("Life is real, unless declared an integer.\n");
- printf("I get 'CoreDumped', therefore I am.\n", "\t\t\t\tAnonymous\n"); }
-