Many library functions, especially those related to the operating system, will notify the program that the function call fails when the execution fails through an external variable named errno.
The following code uses this feature for error handling:
Errno = 0; // * call the library function */If (errno)/* handle errors */
The above processing is incorrect.
To understand this, let's assume what may happen when the fopen function is called. When the fopen function requires a new file for program output,
If a file with the same name already exists, the fopen function will delete it and create a new file. In this way, the fopen function may need to call other library functions to detect files with the same name.
Whether the file already exists. Assume that errno is set when the library function used to detect a file does not exist in the file, the fopen function creates
If no program error occurs in time, errno may still be set.
Therefore, when calling the library function, we should first check the returned value as an error indication, determine that the program execution has failed, and then check errno:
/* Call the library function */If (returned error value)/* Check errno */