C標準庫學習--錯誤處理

錯誤處理 Error Reporting
頭文件 errno.h
volatile int errno;
當函數調用出現錯誤時,這個值會被設置成對應的錯誤碼,可以根據錯誤碼判斷具體出現什麼錯誤。

Error code

Error Message
libc還提供了幾個函數,可以將對應的錯誤碼轉換成用戶能讀懂的錯誤消息,現在來介紹這幾個函數。

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

該函數以errno作爲參數,返回一個指向靜態去錯誤消息的指針。因此該函數不是線程安全的。

例如:打開一個不存在的文件

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(int argc, char **argv){
       FILE *fp = fopen("aaaa.txt", "r");
       if(fp == NULL){
               fprintf(stderr, "%s\n", strerror(errno));

       }
       if(fp) fclose(fp);
       return 0;
}

輸出結果:
$ ./a.out
No such file or directory

#include <string.h>
void perror(const char *messge);

這個函數將錯誤消息輸出到標準錯誤(stderr),所輸出的消息跟strerror輸出的錯誤消息相同,必須在函數執行完立即調用。
參數message可以爲NULL,空字符串或自定義的錯誤消息。輸出結果會自動添加換行符。

例如:

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(int argc, char **argv){
       FILE *fp = fopen("aaaa.txt", "r");
       if(fp == NULL){
               //fprintf(stderr, "%s\n", strerror(errno));
               perror("open file error");
       }
       if(fp) fclose(fp);
       return 0;
}

輸出:
$ ./a.out
open file error: No such file or directory

#include <string.h>
char * strerror_r (int errnum , char * buf , size t n );

這個函數是gnu libc的擴展,這個功能跟strerror相同,只不過,它的消息不是放在靜態存儲區的,而是寫到用戶提供的buf中。這個函數是線程安全的。

例如:

#include <stdio.h>
#include <string.h>
#include <errno.h>

#define BUF_LEN 1024
int main(int argc, char **argv){
       char buf[BUF_LEN] = {0};
       FILE *fp = fopen("xxxx.txt", "r");
       if(fp == NULL){
               (void)strerror_r(errno, buf, BUF_LEN);
               fprintf(stderr, "%s\n", buf);
       }
       if(fp) fclose(fp);
       return 0;
}

輸出:
$ ./a.out
No such file or directory

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章