Idiosyncracies of feof

Shiraz Baig shiraz_baig at yahoo.com
Fri Dec 17 07:01:07 UTC 2010


IdioSyncracies of feof()........
I wrote the following code and wanted to read 16 bytes each time, in a loop.

  while (!feof(filein)) {
      nbytes=fread(bufin, 1, 16, filein);
      printf("Bytes Read = %d\n", nbytes);
  }
  
  I noted that, if the "filein" size is exact multiple of 16 bytes, the
  loop runs n times.  On the other hand if the "filein" size is not exact
  multiple of 16 bytes, the loop runs n-1 times. That cost me 6 hours of
  wasted time!

  I had a file of 84 bytes. While encrypting my loop ran 6 times. But
  unfortunately, encrypted file has to be an exact multiple of 16 bytes,
  ie it was 96 bytes. So, While decrypting, the the loop ran 7 times,
  making me scratch my head for many hours. Because I wanted to write
  same loop for both encrypting and decryption. I could not do so. Then
  I had to put my own check, in addition to the feof() check.  what a
  dumb function, this feof() is. It cannot distinguish that no bytes
  are left and it should not run an extra time.  

  I also tried by putting fread() outside loop and at the end of loop,
  but then my encrypting ran one times less :-(  So back to square one....
  ie putting my own check in the code.

  Am I missing something?

regards
shiraz



      


More information about the redhat-list mailing list