strange issue reading /dev/null

Jeremy Chadwick koitsu at FreeBSD.org
Thu Aug 7 16:25:08 UTC 2008


On Thu, Aug 07, 2008 at 04:46:37PM +0200, Gabor Kovesdan wrote:
> Hello,
>
> I'm wondering why fgetc() returns 0xff if called with /dev/null:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int
> main(void)
> {
>        int      c;
>        FILE    *f;
>
>        f = fopen("/dev/null", "r");
>
>        if (c != EOF)
>                printf("%c\n", fgetc(f));
> }
>
> > gcc foo.c
> > ./a.out
> ÿ
>
> This causes a bug in BSD grep as /dev/null is not distinguished from  
> ordinary files in the code, thus I was expecting it just returned EOF,  
> but in reality this is not the case. How such cases should be handled?

Your code is wrong -- you're not calling feof().  Please read
the RETURN VALUES section of fgetc(3) in full, and slowly.  :-)

And your if() statement serves no purpose there.

-- 
| Jeremy Chadwick                                jdc at parodius.com |
| Parodius Networking                       http://www.parodius.com/ |
| UNIX Systems Administrator                  Mountain View, CA, USA |
| Making life hard for others since 1977.              PGP: 4BD6C0CB |



More information about the freebsd-hackers mailing list