C语言提供了一个全局变量errno来提供程序执行的一些情况。errno在errno.h中声明。
下面这个例子试图打开并不存在的一个文件,然后输出errno的值。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main()
{
int fd;
errno=0;
fd=open("xxx",O_RDWR);//假设xxx不存在
if(errno==0)
{
printf("open successful/n");
}
else
{
printf("fail to open,errno is : %d/n",errno);
exit(1);
}
close(fd);
return 0;
}
输出错误原因
errno只是一个int值,我们必须通过查表才能知道起真正代表的错误原因,要避免这点,可以利用strerror函数:
#include <string.h>
char * strerror(int err);
使用时将error作为参数传入即可。
另一个提供类似功能的函数是perror,它根据errno和传入的字符串,打印一条出错信息,其函数原型如下:
#include <stdio.h>
#include <errno.h>
void perror(const char * pszInfo);
perror的参数iaoshi要输出的字符串,系统自动将使用errno变量映射得到的错误文件描述的字符串连接到参数字符串的后面,该字符串没必要添加'/n',perror函数会自动添加。
以下是一个例子:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
{
int fd;
errno=0;
fd=open("xxx",O_RDWR);//假设xxx不存在
if(fd==-1)
{
perror("fail to open");
exit(1);
}
close(fd);
return 0;
}
将输出
fail to open: No such file or directory