当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C语言中的errno(错误报告)用法

C语言中的errno(错误报告)用法

2018年10月25日  | 移动技术网IT编程  | 我要评论

光速铁匠,欧思范斯,湖北宜都

c语言标准库中的错误报告用法有三种形式。

1errno

errno在头文件中定义,如下

 

#ifndef errno
extern int errno;
#endif

 

外部变量errno保存库程序中实现定义的错误码,通常被定义为errno.h中以e开头的宏,

所有错误码都是正整数,如下例子

# define edom   33      /* math argument out of domain of function.  */

edom的意思是参数不在数学函数能接受的域中,稍后的例子中用到了这个宏。

errno的常见用法是在调用库函数之前先清零,随后再进行检查。

2strerror

strerror在中定义,如下

__begin_namespace_std
/* return a string describing the meaning of the `errno' code in errnum.  */
extern char *strerror (int __errnum) __throw;
__end_namespace_std

函数strerror返回一个错误消息字符串的指针,其内容是由实现定义的,字符串不能修改,但可以在后续调用strerror函数是覆盖。

3perror

perror在中定义,如下

__begin_namespace_std
/* print a message describing the meaning of the value of errno.
   this function is a possible cancellation point and therefore not
   marked with __throw.  */
extern void perror (const char *__s);
__end_namespace_std

函数perror在标准错误输出流中打印下面的序列:参数字符串s、冒号、空格、包含errno中当前错误码的错误短消息和换行符。在标准c语言中,如果s是null指针或null字符的指针,则只打印错误短消息,而不打印前面的参数字符串s、冒号及空格。

下面是几个简单的例子

#include 
#include 
#include 
#include 

int main(void)
{
    errno = 0;
    int s = sqrt(-1);
    if (errno) {
        printf("errno = %d\n", errno); // errno = 33
        perror("sqrt failed"); // sqrt failed: numerical argument out of domain
        printf("error: %s\n", strerror(errno)); // error: numerical argument out of domain
    }

    return 0;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网