C語言中錯誤顯示函式
阿新 • • 發佈:2021-01-12
有兩個比較常用的函式,分別是strerror和perror。
strerror
標頭檔案是string.h,原型為:
char *strerror(int errnum);
接受一個表示錯誤程式碼的整型值,返回錯誤程式碼對應的資訊字串;
perror
標頭檔案是stdio.h,原型為:
void perror(const char *s);
該函式是把errno的錯誤對映為字串,然後在前面拼接字串s和一個冒號(應該是空格+冒號),最後在標準輸出上顯示。
測試程式碼:
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <errno.h> int main(int argc, char** argv) { int fd; fd=open("file_not_exist", O_RDWR); printf("ererno=%d\n",errno); printf("strerror:%s\n",strerror(errno)); perror("perror"); exit(EXIT_SUCCESS); }
執行的結果如下:
可以看到strerror的結果必須使用printf等才能在標準輸出上顯示,而perror直接顯示,各有各的適用場景,perror相對來說簡單高效一些,一個函式就能夠把錯誤顯示在標準輸出上,而strerror則相對靈活一些,有些時候我們還可能要把錯誤資訊提供到別的地方,例如顯示在其他介面,或者寫入日誌、資料庫等,這個時候就像處理字串一樣方便。