Search code examples
cerrnogetc

Read reports Bad File Descriptor despite getc successfully using the same fd to read a char


I have this C code:

FILE * fd = fopen(filename,"rb");
printf("%c ",(char)getc(fd)); // returns expected char
unsigned char buffer[10];
printf("%d ",read(fd, &buffer, 10)); // -1
printf("%d\n",errno); // 9

getc returns a char from the input file, as expected. However read returns an error (-1) and errno is set to 9 (bad file descriptor). Clearly the file descriptor is OK, since getc manages to use it to read a char.

What is the problem here?


Solution

  • fopen and read are functions of different families. The families are:

    • fopen with fread (and also getc), from the C standard library.

    • open with read, from the POSIX specification.

    The first family uses file pointers as FILE* types, while the second one uses file descriptors as int types. You can't mix the two families as long as you don't convert from one file descriptor type to the other. The conversion from FILE* to int is done with the POSIX function fileno.

    In your case, use fread to read from the file.