C语言进阶:glibc学习之错误处理

本文为glibc参考手册及glibc源码的学习笔记,其中或有遗漏、错误或描述不清晰的地方,仅供个人学习记录之用。

  • 错误检查
  • 错误代码
  • 错误相关函数
  • 相关例子

错误检查

Most library functions return a special value to indicate that they have failed. The special value is typically -1, a null pointer, or a constant such as EOF that is defined for that purpose. But this return value tells you only that an error has occurred. To find out what kind of error it was, you need to look at the error code stored in the variable errno. This variable is declared in the header file errno.h. —— [The GNU C Library Reference Manual]
由上可知glibc中有一个用来存储错误代码的变量,c程序在运行时出错后,将第一时间将错误代码的值赋值给变量errno,在errno.h头文件中改变量的定义如下:

volatile int errno;

变量errno在引入头文件errno.h后就可使用。需要注意的是,errno可能随时会发生变化,所以需要及时处理。

错误代码

glibc中的错误代码同样在头文件errno.h中定义,接下来将列举部分错误代码。

int EPERM;//操作不被允许
int ENOTENT;//没有该文件或目录
int ESRCH;//没有进程的PID等于指定的PID
int EINTR;//函数调用中断
int EIO;//输入/输出错误
int ENXIO;//没有指定的设备或地址
int E2BIG;//参数太长
int ENOEXEC;//无效的可执行文件
int EBADF;//无效的文件描述符
int ECHILD;//子进程不存在
int EDEADLK;//避免死锁
int ENOMEM;//内存不可用
int EACCES;//拒绝访问
int EFAULT;//无效地址
int ENOTBLK;//不是块设备文件(当在需要块设备文件的场景下可能会出现此错误)
int EBUSY;//资源不可用
int EEXIST;//文件已存在
int EXDEV;
int ESHUTDOWN;//Socket已经被关闭
...

错误相关函数

关于错误与警告信息相关的处理函数主要用于在编码过程中进行合理规范的错误异常事件处理,在编码时应该合理运用,提高自己代码的规范性及可读性。

/*
*参数:错误代码errnum
*返回值:错误代码所对应的描述
*描述:在string.h中声明
*/
char *strerror(int errnum);

/*
*参数:错误代码errnum;用户自定义buffer;自定义buffer大小
*返回值:错误代码所对应的描述
*描述:错误描述可以通过返回值或buf得到,其与strerror的主要区别在于多加了两个参数,解决了用户在多线程情况下使用*streeror无效的问题。在string.h中声明
*/
char *strerror_r(int errnum,char *buf,size_t n);

/*
*参数:message用户自定义描述
*返回值:空
*描述:将打印如下信息-----message:errno对应的描述,声明在stdio.h
*/
void perror (const char * message );

/*
*参数:status;errnum;format;可变参数
*返回值:空
*描述:将打印如下信息-----程序名:用户自定已信息:errnum对应的描述,声明在error.h
*/
void error (int status , int errnum , const char * format , . . . )

相关例子

#include <errno.h>
#include <error.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int args,char* argv[]){
    char * s = strerror(ENOTSUP);
    char * fileName = "test";
    FILE * stream;
    errno = 0;
    if(NULL == (stream = fopen(fileName,"r"))){
        fprintf(stderr,"strerror测试--file couldn't open:%s\n",strerror(errno));//strerror测试,string.h
        printf("---------------------\n");
        perror("perror测试--读取文件出错");//perror测试,stdio.h
        printf("---------------------\n");
        error(0,errno,"%s","error测试--读取文件出错");//error测试,error.h
        printf("---------------------\n");

        printf("---------------------\n");
    }else{
        return 1;
    }
    return 0;
}

例子运行截图

示例运行截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值