home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16426 < prev    next >
Encoding:
Text File  |  1992-11-12  |  2.0 KB  |  55 lines

  1. Path: sparky!uunet!ferkel.ucsb.edu!taco!rock!stanford.edu!ames!think.com!sdd.hp.com!zaphod.mps.ohio-state.edu!rphroy!einstein!wenner
  2. From: wenner@einstein.eds.com (Rich Wenner)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: problem with foef()
  5. Message-ID: <1267@pascal.einstein.eds.com>
  6. Date: 12 Nov 92 21:38:24 GMT
  7. References: <92316.213238U17868@uicvm.uic.edu> <BxMCIJ.L8M@portal.hq.videocart.com>
  8. Organization: Electronic Data Systems
  9. Lines: 44
  10.  
  11. In article <BxMCIJ.L8M@portal.hq.videocart.com> dfuller@portal.hq.videocart.com (Dave Fuller) writes:
  12. >U17868@uicvm.uic.edu () writes:
  13.  
  14. >: I am reading a binary file with fread. The file has only two records, each
  15. >: 193 bytes. The problem is that after reading the second record (structure)
  16. >: the feof function does not detect the end of file and goes through the loop
  17. >: one more time (third time).
  18.  
  19. >:   while(!feof(file_pointer))
  20. >:   {
  21.           [fread() call and other processing omitted]
  22. >:   }/* end while */
  23.  
  24. And confusion soon follows.
  25.  
  26. >a couple of things. feof returns non-zero after the first attempt to read
  27. >PAST the end of the file. possibly you have a spare char out there that
  28. >makes it NOT a read past EOF.
  29.  
  30. NO!!!  You don't have to have any 'spare' characters to explain the behavior
  31. of this code.  The second read reads UP TO the end, not past it.  Even without
  32. spare characters, this is not sufficient to make feof() return a true value.
  33. This is why I tell my students not to use feof() for loop control.  Instead,
  34. I recommend a structure like the following:
  35.  
  36.     while ( fread( buffer, element_size, num_elems, file ) == num_elems )
  37.     {
  38.         /* process the stuff we read */
  39.     }
  40.  
  41.     if ( feof( file ) )
  42.     {
  43.         /* ok, we finihsed the whole file */
  44.     }
  45.     else
  46.     {
  47.         /* uh-oh, something went wrong */
  48.     }
  49.  
  50. -- 
  51. Rich Wenner              | Subject and verb always has to agree.
  52. wenner@csid.gmeds.com    | Consult a dictionary frequently to avoid mispelling.
  53.                          | Hopefully, you will use words correctly,
  54. #include <stddisclaim.h> |            irregardless of how others use them.
  55.