Is EOF errno installed?

I always struggle with return values ​​of system calls - they are just so inconsistent! I usually check if they are NULL or -1, and then call perror. However, for fgets, the manual page says:

gets()and fgets()return s on successful completion, and NULLon error or on completion of the file when no characters were read.

which means that the return value is NULLnot necessarily an error - it could also be EOF. Is errno installed when it reaches the end of the file? Can I call perrorin this case?

If not, what is the general way to determine if the call caused an error compared to EOF. I want to use perrorwith a NULL string for errors and a custom string for EOF.

+4
source share
2 answers

Use ferrorand feofto distinguish between error and EOF. There is no general way to find out what the mistake was if there was a mistake, but you can say that it is.

The C standard (f)gets(s (f)getc) are not required to be set errno, although the implementation of the corresponding library can be set errnoto a non-zero value to a large extent as desired.

Posix , (f)get{c,s} errno , , , ( ferror). , errno 0, errno , . errno , fgets. , errno () EOF, .

+6

fputs, , EOF errno. , , , , . fputs , , EOF . , , fputs . , fputs.

if (fputs(buffer, stdout) == EOF)
{
  fprintf(stderr, "fputs returned EOF: %s\n", strerror(errno));
  // .. and now do whatever cleanup you need to do.
  // or be lazy and exit(-1)
}

, fputs EOF. EOF , , man fputs, if , errno.

(1) ? , .

(2) fprintf? , (stderr... , stdout, ).

(3) ? , string.h, . , errno. string.h strings.h, BSD linux, strerror (3).

: , . fgets, fputs.

fgets,

if (fgets(buffer, BUF_SIZE, myFile) == NULL)
{ 
  // your file isn't readable. Check permissions
  fprintf(stderr, "fgets error occurred: %s\n," strerror(errno));
  // do cleanup
}
// special: you also need to check errno AFTER the if statement...

, , , - , , . - , fgets if. , - .

, . . Linux. , , - " ", errno == EBADF

+1

Source: https://habr.com/ru/post/1533108/


All Articles