C语言中关于错误输出的函数

1. errno

说明:errno是一个全局整形变量,定义在errno.c,声明在errno.h

头文件:#include <errno.h>

功能:输出出错原因

示例

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main()
{
    int fd;
    errno=0;
    fd=open("/home/admin/nothing.txt",O_RDWR);
    if(errno==0)
      printf("Sucessful\n");
    else
    {
        printf("Fail to open, errno is: %d\n", errno);
        exit(1);
    }
    close(fd);
    return 0;

}

结果:Fail to open, errno is: 2

2. strerror()

声明:char * strerror( int errno );

头文件:#include <string.h>

功能:根据错误号返回错误的描述

返回值返回出错字符串

示例

#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("/home/admin/nothing.txt",O_RDWR);
    if(errno==0)
      printf("Sucessful\n");
    else
    {
        int err=errno;
        printf("Fail to open, the reason is: %s\n", strerror(err));
    }
    close(fd);
    return 0;
}

结果:Fail to open, the reason is: No such file or directory

3. perror()

声明:void perror( const char *pszInfo );

头文件:#include <stdio.h>

                #include <errno.h>

功能char *pszInfo表示要输出的字符串,系统自动将使用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("/home/admin/nothing.txt",O_RDWR);
    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、付费专栏及课程。

余额充值