错误代码获取相应的错误描述

131 阅读2分钟

错误代码获取相应的错误描述

strerror()

要从错误代码获取到相应的错误描述, 可以使用strerror()函数得到错误信息的字符串, 打印即可

strerror() 是一个 C 语言标准库函数,用于将errno错误码转换为对应的错误信息字符串。

  • ps: 记得引用errno.h

如例:

 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <errno.h>
 #include <string.h>
 ​
 /*自定义的错误处理函数*/
 void my_err(const char * err_string, int line)
 {
     fprintf(stderr, "line:%d  ", line);
     //perror(err_string);
     //perror(NULL);
     printf("\nerr:%s errno:%d\n", strerror(errno), errno);
     exit(1);
 }
 ​
 /*自定义的读数据函数*/
 int my_read(int fd)
 {
     int     len;
     int     ret;
     int     i;
     char    read_buf[64];
 ​
     /*获取文件长度并保持文件读写指针在文件开始处*/
     if (lseek(fd, 0, SEEK_END) == -1) {
         my_err("lseek", __LINE__);
         /* __LINE__ 是一个预定义宏,表示当前代码所在的行号,用于获取错误发生的位置 */
     }
     if ((len = lseek(fd, 0, SEEK_CUR)) == -1) { // 前一个lseek调用已经将读写指针指向文件末尾
         my_err("lseek", __LINE__);
     }
     if ((lseek(fd, 0, SEEK_SET)) == -1) { // 指向文件开头
         my_err("lseek", __LINE__);
     }
     
     printf("len:%d\n", len); // 在进行实验时成功执行了此条命令,说明前面成功读取文件长度,并指向文件开头
     /*读数据*/
     if ((ret = read(fd, read_buf, len)) < 0) { // 将整个文件复制进read_buf
         my_err("read", __LINE__);
     }
     
     /*打印数据*/
     for (i=0; i<len; i++) {
         printf("%c", read_buf[i]);
     }
     printf("\n");
 ​
     return ret;
 }
 ​
 int main()
 {
     int fd;
     char    write_buf[32] = "Hello World!";
 ​
     /*在当前目录下创建文件example_63.c*/
     if ((fd = creat("example_63.c", S_IRWXU)) == -1) {
     //if ((fd = open("example_63.c", O_RDWR|O_CREAT|O_TRUNC, S_IRWXU)) == -1) {
         my_err("open", __LINE__);
     } else {
         printf("create file success\n");
     }
     
     /*写数据*/
     if (write(fd, write_buf, strlen(write_buf)) != strlen(write_buf)) {
         my_err("write", __LINE__);
     }
     my_read(fd);
 ​
     /*演示文件的间隔*/
     printf("/*--------------------*/\n");
     if (lseek(fd, 10, SEEK_END) == -1) {
         my_err("lseek", __LINE__);
     }
     if (write(fd, write_buf, strlen(write_buf)) != strlen(write_buf)) {
         my_err("write", __LINE__);
     }
     my_read(fd);
     
     close(fd);
     return 0;
 } 
 ​
 # 结果
 create file success
 len:12
 line:41  
 err:Bad file descriptor errno:9
 ​

关于perror()

perror()是一个 C 语言标准库函数,用于将最近的一次系统调用错误信息输出到标准错误流 stderr,并附加一个自定义的错误信息前缀。

perror()函数的参数 err_string 是一个字符串指针,用于指定输出的错误信息前缀。如果 err_string 为 NULL,则只输出系统调用错误信息,不添加前缀。

让我们将例子中my_err函数的printf注释掉, 换用perror的结果如下:

 # perror(err_string)
 create file success
 len:12
 line:38  read: Bad file descriptor
 ​
 # perror(NULL)
 create file success
 len:12
 line:42  Bad file descriptor

额外的小知识

LINE