[gshyam: fgetc returns no error for bad file descriptor]

Christopher Faylor cgf@redhat.com
Mon Mar 8 19:57:00 GMT 2004

[reply-to set]
This observation, sent to the cygwin mailing list, is apparently correct.
fgetc doesn't set errno when trying to read from an fp that is only open
for writing.

The attached test program results in this output:

  fp 0xc30c4c, fd 4
  -1 = fgetc
  fgetc: No error
  -1 = read
  read: Bad file descriptor


----- Forwarded message from Ghanshyam <gshyam> -----

From: Ghanshyam
To: cygwin
Subject: fgetc returns no error for bad file descriptor
Date: Mon, 8 Mar 2004 20:11:37 +0000 (GMT)

Hi All,
    The 9th assertion of fgetc in "IEEE std 2003.1-1992 Test Methods for
Measuring Conformance to Posix-Part1 System Interface" document states:
    When the stream pointer argument addresses a file descriptor that
is not open for reading, then a call to fgetc()returns a value of 
EOF and sets errno to [EBADF].
The current implementation does not set any errno. It says "No error". 


----- End forwarded message -----
-------------- next part --------------
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/fcntl.h>

main (int argc, char **argv)
  FILE *fp = fopen ("/dev/null", "w");
  int fd = open ("/dev/null", O_WRONLY);
  printf ("fp %p, fd %d\n", fp, fd);
  char buf[4];
  printf ("%d = fgetc\n", fgetc (fp));
  perror ("fgetc");
  printf ("%d = read\n", read (fd, buf, 1));
  perror ("read");
  return 0;

More information about the Newlib mailing list