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

来源:互联网 发布:macbook使用windows 编辑:程序博客网 时间:2024/05/22 05:07

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

1errno

errno<errno.h>头文件中定义,如下

#ifndef errnoextern int errno;#endif

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

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

# define EDOM   33      /* Math argument out of domain of function.  */

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

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

2strerror

strerror<string.h>中定义,如下

__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<stdio.h>中定义,如下

__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语言中,如果sNULL指针或NULL字符的指针,则只打印错误短消息,而不打印前面的参数字符串s、冒号及空格。

下面是几个简单的例子

#include <stdio.h>#include <errno.h>#include <string.h>#include <math.h>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;}

1 0
原创粉丝点击