首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Linux C 文件操作錯誤碼打印:errno 與 strerror 完整對照表與實戰模式

     編輯:關於C語言

核心頭文件與函數

#include <errno.h>   // extern int errno;
#include <string.h>  // char *strerror(int errnum);

錯誤碼完整對照表(節選常見)

errno宏定義含義
0-Success
1EPERMOperation not permitted
2ENOENTNo such file or directory
13EACCESPermission denied
21EISDIRIs a directory
24EMFILEToo many open files
28ENOSPCNo space left on device
32EPIPEBroken pipe

完整列表可運行以下代碼自動生成:

for (int i = 0; i < 134; i++) 
    printf("%3d: %s\n", i, strerror(i));

標準錯誤處理模式

int fd = open("file.txt", O_RDONLY);
if (fd == -1) {
    fprintf(stderr, "[%s:%d] open failed: %s (errno=%d)\n",
            __FILE__, __LINE__, strerror(errno), errno);
    return -1;
}

進階封裝宏

#define CHECK_SYS(call) do { \
    if ((call) == -1) { \
        fprintf(stderr, "[%s:%d] %s failed: %s\n", \
                __FILE__, __LINE__, #call, strerror(errno)); \
        exit(EXIT_FAILURE); \
    } \
} while(0)

// 使用
CHECK_SYS(fd = open("a.txt", O_RDONLY));
CHECK_SYS(n = read(fd, buf, sizeof(buf)));

注意事項

  • errno 為線程局部變量,多線程安全。
  • 僅在系統調用返回 -1 時檢查 errno,成功調用不保證 errno 為 0。
  • perror("msg") 等價於 fprintf(stderr, "msg: %s\n", strerror(errno))。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved