Use errno to debug the program

Source: Internet
Author: User

 

 

The C language provides a global variable errno for program execution. Errno is declared in errno. h.

The following example attempts to open a non-existing file and then outputs the errno value.

 

# Include <stdio. h>

# Include <stdlib. h>

# Include <fcntl. h>

# Include <unistd. h>

# Include <errno. h>

 

Int main ()

{

Int FD;

Errno = 0;

 

FD = open ("XXX", o_rdwr); // assume XXX does not exist

 

If (errno = 0)

{

Printf ("Open successful/N ");

}

Else

{

Printf ("fail to open, errno is: % d/N", errno );

Exit (1 );

}

 

Close (FD );

 

Return 0;

}

 

Output Error cause

Errno is only an int value. We must look up the table to identify the cause of the Error. To avoid this, we can use the strerror function:

 

# Include <string. h>

Char * strerror (int err );

 

Use error as a parameter.

 

Another function that provides similar functions is perror, which prints an error message based on errno and the input string. Its function prototype is as follows:

 

# Include <stdio. h>

# Include <errno. h>

Void perror (const char * pszinfo );

 

The iaoshi parameter of perror is the string to be output. The system automatically connects the string described in the error file mapped using the errno variable to the end of the parameter string. You do not need to add '/N' to the string ', the perror function is automatically added.

 

 

The following is an example:

 

# Include <stdio. h>

# Include <stdlib. h>

# Include <fcntl. h>

# Include <unistd. h>

# Include <errno. h>

# Include <string. h>

 

Int main ()

{

Int FD;

Errno = 0;

 

FD = open ("XXX", o_rdwr); // assume XXX does not exist

 

If (FD =-1)

{

Perror ("fail to open ");

Exit (1 );

}

 

Close (FD );

 

Return 0;

}

 

Output

Fail to open: no such file or directory

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.