perror函数
perror
函数与strerror
函数都是跟errno有关系的函数, 而strerror函数不明白的可以去看一看, 了解一下. 现在, 主要说的是perror.
#include<stdio.h> // 头文件
#include<stdlib.h>
void perror(const char *s); // 函数声明
perror ( )用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到 标 准 设备 (stderr) .参数 s 是加上对错误的描述. 而错误的编号是放在errno
中, perror会去自动调用 errno 的错误提示. 大致有点像
void perror(char char *s)
{
printf("%s %s", s, strerror(errno));
}
当你调用某些函数出错时, 就会自动修改errno
的值. perror
函数只是输出你写的提示和现在的errno所对应的错误.
就像这样打开一个不存在的文件, 就会将错误编号放在error中, 而perror就是输出上次编号的错误提示.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <stdlib.h>
int main()
{
open("function_dou", O_WRONLY);
perror("function_dou don't error");
return 0;
}
运行结果:
rpz@funct:~$ ./a.out
function_dou don't error: No such file or directory
在这里还是想要说一下, 关于errno的数据类型, 它并不是一个 int, long, 等类型, 它是一个定义在errno.h头文件中的一个宏定义. 它可以在不同的进程和线程中分别调用, 同一时间允许有不同的值(恩? 是不是很不明白, 同一东西, 同一时间有不同的值? 是不是觉得很不可思议, 是不是我写错了, 不是!). 具体的实现, 我会总结errno. 在网上应该也能找到, 我也是在其他地方看到才知道的.