eof

jjnoakes at gmail.com jjnoakes at gmail.com
Sat Dec 8 12:59:35 EST 2007


On Nov 22, 10:37 am, Hrvoje Niksic <hnik... at xemacs.org> wrote:
>
>   def read(self, size=None):
>       if size is None:
>           val = file.read(self)
>           self.eof = True
>       else:
>           val = file.read(self, size)
>           if len(val) < size:
>               self.eof = True
>       return val

Anyone using this routine must be careful not to fall in to this trap.

  !f.eof implies f.read() will return data

For example, with a 5-byte file:

  f = MyFile(5byte.bin)
  data = f.read(5)
  f.eof # ==> False
  data = f.read(5) # ==> Empty String
  f.eof # ==> True

In other words, don't rely on "f.eof" telling you that there is or is
not more data... on Unix systems, no matter what, you ALWAYS have to
read past EOF to detect it. Languages (like C with FILE*, or Ruby, or
anything else) that detects EOF either does it incorrectly, or (what
usually happens) reads 1 byte to see if they get an empty string back
from the OS.

Think about this: If you have to read 1 byte every time you want to
check for EOF, what happens if you are reading from a network stream?
That 1-byte read may take a while, waiting for data to be sent over
the wire. What a performance hit.

-JJ



More information about the Python-list mailing list