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

2

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.

Yowl answered 12/4, 2012 at 14:1 Comment(4)
you could use perror() to get a more descriptive error infoYalonda
@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).Yowl
@Yalonda 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.Ladon
@ydroneaud man 3 ferror ferror() never fails or sets the errno so it should be ok ,fgets would have set the errno.Yalonda
T
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)
  • ...
Telltale answered 12/4, 2012 at 14:20 Comment(2)
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".Yowl
@LieRyan device is full would that affect fgets ?Yalonda
K
1

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
Kuehl answered 23/11, 2020 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.