C traps and defects-use errno to detect errors

Source: Internet
Author: User

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 */

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.