lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

John D. Ramsdell wrote:
> While almost all of the code was clear to me, I am unable to explain
> one line of code in getF.  Why is it necessary to call feof before the
> fread?  Won't fread return 0 if feof returns true?  It seems that
> fread correctly handles the case of EOF.
>   if (feof(lf->f)) return NULL;      /* Why? */
>   *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
>   return (*size > 0) ? lf->buff : NULL;

It's a precaution to not require excessive "CTRL-D"s when
reading from a terminal/stdin. (It may also help on not 100%
correct stdio implementations.)

Contrary to files, an EOF is not a permanent conditions on
terminal devices: one fread/getc/etc may signal EOF (because
the user pressed CTRL-D) but the next fread will happily try
to read more data (and block).

Try "lua -" and count how many "CTRL-D"s are required with
and without that "if (feof..." line.

Ciao, ET.