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

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

1、errno

errno在<errno.h>头文件中定义,如下
#ifndef errnoextern int errno;#endif
外部变量errno保存库程序中实现定义的错误码,通常被定义为errno.h中以E开头的宏,
所有错误码都是正整数,如下例子
# define EDOM 33 /* Math argument out of domain of function. */
EDOM的意思是参数不在数学函数能接受的域中,稍后的例子中用到了这个宏。
errno的常见用法是在调用库函数之前先清零,随后再进行检查。

2、strerror
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函数是覆盖。

3、perror
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语言中,如果s是NULL指针或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;}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值