设为首页 加入收藏

TOP

C语言中的errno(错误报告)用法
2015-11-19 23:06:53 来源: 作者: 【 】 浏览:10
Tags:言中 errno 错误 报告 用法

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; } 
     
    
   
  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Swift 与Objective-c语法参照 下一篇循环队列(C语言版)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: