通过strerror获取详细的错误信息

来源:互联网 发布:python日期格式 编辑:程序博客网 时间:2024/06/15 01:03

Linux环境下面,C/C++代码在调用库函数出错之后,可以调用strerror(errno)获取详细的出错信息(human readable)。


示例:

#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <string.h>#include <errno.h>#include <stdio.h>int main(){    const char *NOT_EXIST_FILE = "./not_exist_file_name.nefn";    struct stat st;    int ret;    ret = stat(NOT_EXIST_FILE, &st);    if (-1 == ret) {        printf("Error(%d): %s\n", errno, strerror(errno));    } else {        printf("Stat ok\n");    }    return 0;}

运行结果:

flying-bird@flying-bird:~/examples/cpp/strerror$ gcc main.cflying-bird@flying-bird:~/examples/cpp/strerror$ ./a.out Error(2): No such file or directoryflying-bird@flying-bird:~/examples/cpp/strerror$ 


作为一种编写习惯(或规范),每个调用之后都需要对返回值进行检查,否则可能极大降低代码调试效率。

0 0
原创粉丝点击