Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 21 May 2005 23:52:22 +0300
From:      Giorgos Keramidas <keramida@freebsd.org>
To:        Steve Kargl <sgk@troutmask.apl.washington.edu>
Cc:        freebsd-standards@freebsd.org
Subject:   Re: Read /dev/null differs from POSIX
Message-ID:  <20050521205222.GA1014@gothmog.gr>
In-Reply-To: <20050521193605.GB51782@troutmask.apl.washington.edu>
References:  <20050521193605.GB51782@troutmask.apl.washington.edu>

next in thread | previous in thread | raw e-mail | index | archive | help
On 2005-05-21 12:36, Steve Kargl <sgk@troutmask.apl.washington.edu> wrote:
> >From http://www.opengroup.org/onlinepubs/009695399/toc.htm
>
>    /dev/null -- An infinite data source and data sink.  Data
>    written to /dev/null shall be discarded.  Reads from
>    /dev/null shall always return end-of-file (EOF).
>
> This program
>
>   #include <stdio.h>
>   int main(void) {
>      int i=0,j;
>      FILE *fp;
>      fp = fopen("/dev/null", "r");
>      while(fread(&j, sizeof(int), 1, fp) != 1) {
>        i++;
>        if (i == 5) break;
>      }

The condition of the while loop above is bogus.  fread() of any amount
of data from /dev/null returns 0 items, but the loop will still iterate,
increasing i as if some data was read.

Rewriting the loop as shown below reveals that /dev/null indeed works as
expected:

        for (i = 0; fread(&j, sizeof(j), 1, fp) == 1; i++)
                printf("step %d read %lu bytes\n", i,
                    (unsigned long)sizeof(j));

This *NEVER* prints a "step X read Y bytes" message from /dev/null.

>         if (j == EOF)
>                 printf("EOF\n");
>         else
>                 printf("j = %d\n", j);

This is bogus.  fread() doesn't set the output buffer to EOF but marks
the `fp' stream as end-of-file'd.  The correct way to check for
end-of-file on stdio.h streams is:

	if (feof(fp))
		... ;



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20050521205222.GA1014>