Any function can set errno, but only if it sets a nonzero value. The ANSI C specification states:
Errno is zero when the program starts, but it is never set to zero by any library function. * The value of errno can be set to a non-zero library function call, is there an error if the use of errno is not documented in the description in the standard.
* Therefore, a program that uses errno to check for errors should set it to zero before calling the library function, then check it before calling the library function later.
So, if you use errno, the best practice approach is to set the value to 0 just before the library call, which may fail, and read it immediately. In the above example, just add something like:
int localErrno = errno
immediately before the printf statement and use localErrno for your switch. This, of course, assumes that there are no library calls between the failed function and the printer call. If you need to save errno after an unsuccessful call and pass it to your print function. A.
user511089
source share