home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ferkel.ucsb.edu!taco!rock!stanford.edu!ames!think.com!sdd.hp.com!zaphod.mps.ohio-state.edu!rphroy!einstein!wenner
- From: wenner@einstein.eds.com (Rich Wenner)
- Newsgroups: comp.lang.c
- Subject: Re: problem with foef()
- Message-ID: <1267@pascal.einstein.eds.com>
- Date: 12 Nov 92 21:38:24 GMT
- References: <92316.213238U17868@uicvm.uic.edu> <BxMCIJ.L8M@portal.hq.videocart.com>
- Organization: Electronic Data Systems
- Lines: 44
-
- In article <BxMCIJ.L8M@portal.hq.videocart.com> dfuller@portal.hq.videocart.com (Dave Fuller) writes:
- >U17868@uicvm.uic.edu () writes:
-
- >: I am reading a binary file with fread. The file has only two records, each
- >: 193 bytes. The problem is that after reading the second record (structure)
- >: the feof function does not detect the end of file and goes through the loop
- >: one more time (third time).
-
- >: while(!feof(file_pointer))
- >: {
- [fread() call and other processing omitted]
- >: }/* end while */
-
- And confusion soon follows.
-
- >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.
-
- NO!!! You don't have to have any 'spare' characters to explain the behavior
- of this code. The second read reads UP TO the end, not past it. Even without
- spare characters, this is not sufficient to make feof() return a true value.
- This is why I tell my students not to use feof() for loop control. Instead,
- I recommend a structure like the following:
-
- while ( fread( buffer, element_size, num_elems, file ) == num_elems )
- {
- /* process the stuff we read */
- }
-
- if ( feof( file ) )
- {
- /* ok, we finihsed the whole file */
- }
- else
- {
- /* uh-oh, something went wrong */
- }
-
- --
- Rich Wenner | Subject and verb always has to agree.
- wenner@csid.gmeds.com | Consult a dictionary frequently to avoid mispelling.
- | Hopefully, you will use words correctly,
- #include <stddisclaim.h> | irregardless of how others use them.
-