使用errno调试程序

 

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值