2

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.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
  • you could use `perror()` to get a more descriptive error info – keety Apr 12 '12 at 14:05
  • @keety: I was deciding on how my program should handle the situation when there is an error in the stream, whether to just perror and quit or whether to perror and recover (reset the error flag and continue) or whether to do something else. To make that decision, I have to know all the possible causes of errors (or at least the common ones). – Lie Ryan Apr 12 '12 at 14:11
  • @keety but `ferror()` is not supposed to update `errno` if the stream is in error, so it's probably too late to use `perror()`. @lie-ryan must use `perror()` after failed `fgets()` call. – Yann Droneaud Apr 12 '12 at 14:13
  • @ydroneaud `man 3 ferror` ferror() never fails or sets the errno so it should be ok ,fgets would have set the `errno`. – keety Apr 12 '12 at 14:20

2 Answers2

2

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)
  • ...
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • the first 5 reasons (failure, pulled out, switched off, ejected, connection lost) are the same, that is "the device is gone" (although it could probably be distinguished between normal ejection and abnormal/unexpected ejection). So, currently there are two reasons: "the device is gone" and "the device is full". – Lie Ryan Apr 12 '12 at 14:29
  • @LieRyan device is full would that affect `fgets` ? – keety Apr 12 '12 at 14:52
0

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
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256