头文件
#include< stdio.h>注意
不可以掉了这个头文件,perror是包含在 stdio.h这个文件里的//定义函数
void perror(const char *s); 例如:perror ("open_port");
char
*
strerror
(interrnum);
函数说明
perror ( )用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到 标 准 设备 (stderr) 。参数 s 所指的字符串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量error 的值来决定要输出的字符串。 在库函数中有个error变量,每个error值对应着以字符串表示的错误类型。当你调用"某些"函数出错时,该函数已经重新设置了error的值。perror函数只是将你输入的一些信息和现在的error所对应的错误一起输出。
strerror( )通过标准错误的标号,获得错误的描述字符串 ,将单纯的错误标号转为字符串描述,方便用户查找错误。
perror和strerror都是C语言提供的库函数,用于获取与erno相关的错误信息,区别不大,用法也简单。最大的区别在于perror向stderr输出结果,而 strerror向stdout输出结果。
测试用例
test.c文件
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char* argv[])
{
FILE *fp;
if ((fp = fopen(argv[1], "r")) == NULL)
{
perror("perror:");
printf("strerror:%s\n", strerror(errno));
}
return 0;
}
运行结果:
root@ubuntu:/nfsroot/exercise# gcc test.c -o test
root@ubuntu:/nfsroot/exercise#
root@ubuntu:/nfsroot/exercise# ls
led led.c led.c~ test test.c test.c~
root@ubuntu:/nfsroot/exercise#
root@ubuntu:/nfsroot/exercise#
root@ubuntu:/nfsroot/exercise# ./test
perror:: Bad address
strerror:Bad address
root@ubuntu:/nfsroot/exercise# ./test nofile
perror:: No such file or directory
strerror:No such file or directory
root@ubuntu:/nfsroot/exercise#