What are the possible error conditions on a stream that will cause ferror() to be set?

323 views Asked by At

Some operations to read and write from streams may set the error flag in a stream, which can be tested using ferror(stream), while I'm quite sure this must be a frequently asked question, I wasn't able to find a list of all the possible causes of errors in SO or in the general web. What could cause ferror() to be set?

In particular, I'm looking for the possible causes of errors when doing fgets() on the standard input on Minix 3, but I'm looking for a more general list as well.

2

There are 2 answers

2
Jonathan Leffler On BEST ANSWER

There isn't any simple list of possible errors. However, depending on the device you're reading from or writing to, the problems could include:

  • Device fails (short circuits, overheats, dies of old age, ...)
  • Device is pulled out of machine (USB stick)
  • Device is switched off or loses power (external disk drive)
  • Device is ejected (CD-ROM)
  • Network connection is lost (SAN, NAS)
  • Device is full (no space left for writing)
  • ...
0
chux - Reinstate Monica On

What are the possible error conditions on a stream that will cause ferror() to be set?

One of several possibilities: Attempting a wrong direction I/O operation sets the error indicator.

#include <stdio.h>
int main(void) {
  FILE *f = fopen("t", "w");
  if (f) {
    int ch = fgetc(f);
    printf("ch %d\n", ch);
    printf("Error %d\n", ferror(f));
    printf("EOF %d\n", feof(f));
    fclose(f);
  }
}
 

Output

ch -1
Error 1
EOF 0