home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!portal!dfuller
- From: dfuller@portal.hq.videocart.com (Dave Fuller)
- Subject: Re: problem with foef()
- Message-ID: <BxMCIJ.L8M@portal.hq.videocart.com>
- Organization: VideOcart Inc.
- X-Newsreader: Tin 1.1 PL3
- References: <92316.213238U17868@uicvm.uic.edu>
- Date: Thu, 12 Nov 1992 19:51:54 GMT
- Lines: 65
-
- U17868@uicvm.uic.edu () writes:
- : i
- : I am reading a binary file with fread. The file has only two records each of si
- : ze 193 bytes. The problem is that after reading the second record (structure) t
- : he feof function does not detects the end of file and goes through the loop one
- : more time (third time). I check with the ftell fucntion the position of the
- : file_pointer (pointer to the file that I am reading). First time it gives the p
- : osition at 193 i.e after reading the first record. Second time it shows the pos
- : ition of the file_pointer at 386 which is correct. Now, I don't have any more r
- : ecords in the file. But, it goes again and reads the same last record again. Th
- : e position of the file_pointer is still 386. After reading the same record, feo
- : f detects the end of file and returns. any suggestions
- : thanks in advance
- : u17868@uicvm.cc.uic.edu
- : sikander
- : my program is listed below
- :
- : #include "header.h"
- : void dispdail(date)
- : char date[9];
- : {
- : int i,j, a;
- : FILE *file_pointer;
- : struct activity temp;
- : file_pointer = fopen("activity.dat","rb");
- : fseek(file_pointer,0,0);
- :
- : while(!feof(file_pointer))
- : {
- : fread(&temp, sizeof(temp),1,file_pointer);
- : j = strcmp(date,temp.date);
- : if(j == 0)
- : printf("%s",temp.date);
- :
- : if(a = (feof(file_pointer)) != 0)
- : {
- : fclose(file_pointer);
- : return;
- : }
- : }/* end while */
- :
- : } /* end dispdail */
-
- a couple of things. feof returns non-zero after the first attempt to read
- PAST the end of the file. possibly you have a spare char out there that
- makes it NOT a read past EOF.
-
- also fread returns the number of elements read, you don't check this value.
-
- here is what i believe happens:
- after the 2nd read, feof doesn't return non-zero
- fread can't read the element and returns a 0 for # of elements read
- (it is at this point that the file pointer is positioned at the EOF)
- ( also fread won't null the buffer. if it reads 0 items, it leaves
- the buffer intact. this is why you see all of the information from
- the 2nd read a 3rd time)
- the next feof does try to read past EOF and the boolean test works.
-
-
- what you will want to do to guarantee success is to test the return
- value of fread also.
-
- Dave Fuller
- dfuller@portal.hq.videocart.com
-
-