stream.getc() doesn't recognize eof

Regan Heath regan at netmail.co.nz
Thu Mar 13 05:43:26 PDT 2008


Brian White wrote:
> I was looking through the std.stream code of Phobos and found this 
> function:
> 
>   // reads and returns next character from the stream,
>   // handles characters pushed back by ungetc()
>   // returns char.init on eof.
>   char getc() {
>     char c;
>     if (prevCr) {
>       prevCr = false;
>       c = getc();
>       if (c != '\n')
>         return c;
>     }
>     if (unget.length > 1) {
>       c = cast(char)unget[unget.length - 1];
>       unget.length = unget.length - 1;
>     } else {
>       readBlock(&c,1);
>     }
>     return c;
>   }
> 
> 
> Is there something I don't understand?  How does it recognize EOF?  The 
> "readBlock" function is defined as returning 0 (zero) if there is no 
> more data but its return value in not checked.

At EOF readBlock returns 0, but more importantly it does not modify the 
value of 'c' which it is passed.

The value of 'c' is char.init (due to D's automatic initialisation of 
variables to their init value)

So, because c == char.init and nothing has modified it, the path which 
calls readBlock will return char.init when EOF is reached.

:)

Regan


More information about the Digitalmars-d-learn mailing list