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

Bug#1986: stdio broken? Strange behaviour of fgets() and scanf()



Package: libc5
Version: 5.2.16-1

(My libc5-dev version is also 5.2.16-1)

The following program (which is similar in structure to one of the
programs used in building xlib) loops forever when it reaches EOF on stdin:

#include <stdio.h>

int main(int argc, char **argv)
{
  int ksnum,i;
  char buf[1024];
  long val;
  char *c;

  printf("EOF is %d\n",EOF);

  for (ksnum=0; 1; c=fgets(buf,sizeof(buf),stdin)) {
    printf("c is %p\n",c);
    i=scanf("#define XK_%s 0x%lx", buf, &val);
    printf("i is %d\n",i);
    if (i==EOF)
      break;
  }
  printf("Finished.\n");
}

Sample output (running it on its own source code):

myrddin:~/compsci/c$ ./testeof <testeof.c
EOF is -1
c is (nil)
i is 0
c is 0xbffff5c4
i is 0
c is 0xbffff5c4
i is 0
[...]
c is 0xbffff5c4
i is 0
c is 0xbffff5c4
i is 0
c is (nil)
i is 0
[the next two lines...]
c is (nil)
i is 0
[...are repeated forever]

Two things are strange: the first call to fgets() returns nil, and calls
to scanf() once end-of-file has been reached return 0 rather than EOF (-1).

This worked under libc5-5.2.9-2. I noticed because it made my X build
hang; this had never happened before.

The man page for scanf says:

RETURN VALUES
       These functions return the number of input items assigned,
       which can be fewer than provided for, or even zero, in the
       event  of  a matching failure.  Zero indicates that, while
       there was input available, no conversions  were  assigned;
       typically  this is due to an invalid input character, such
       as an alphabetic character for  a  `%d'  conversion.   The
       value  EOF  is  returned if an input failure occurs before
       any conversion such as an end-of-file occurs. If an  error
       or end-of-file occurs after conversion has begun, the num-
       ber of conversions which were  successfully  completed  is
       returned.

The man page for fgets() says:

       gets() and fgets() return s on success, and NULL on end of
       file or error.

Steve Early
sde1000@cam.ac.uk


Reply to: