1. 程式人生 > >【轉載++】C/C++錯誤分析errno,perror,strerror和GetLastError()函數返回的錯誤代碼的意義

【轉載++】C/C++錯誤分析errno,perror,strerror和GetLastError()函數返回的錯誤代碼的意義

urn ali blog 查看 情況下 常見 ast mos 運行

本文是上一篇“fopen返回0(空指針NULL)且GetLastError是0”的側面回應。聽趕來多麽地正確和不容置疑,返回NULL時調用GetLastError來看看報錯啊,但當時卻返回了0,大家都覺得系統哪裏出了大問題。事實上,正如:http://www.runoob.com/cprogramming/c-function-fopen.html ,又http://www.cplusplus.com/reference/cstdio/fopen/ 中所開示的那樣,如果返回NULL請查看errno值,在大多數情況下errno值也會被置於依賴於系統的錯誤碼之中”。很顯然,上文中提及的句柄不足的情形下時GetLastError並沒有被賦值。另一方面,調用C的庫函數fopen(全小寫)之後又調用Windows的API GetLastError(首字母大寫)本身就有些突兀。【換句話說】如果調用fopen則後面調用errno,調用GetLastError前請調用Windows API(這裏對應的是CreateFile)。

該函數返回一個 FILE 指針。否則返回 NULL,且設置全局變量 errno 來標識錯誤。
On most library implementations, the errno variable is also set to a system-specific error code on failure.

如下轉載:https://www.cnblogs.com/gjianw217/p/3251928.html

在C語言編譯中,經常會出現一些系統的錯誤,這些錯誤如果在編譯的時候不能很好的“預見”,會使系統“崩潰”,常見的捕獲錯誤函數有:

errno

#include<errno.h>

這個變量是程序默認的參數,並不需要程序員顯式定義,但必須聲明:extern int errno; 並且需要包含頭文件 errno.h

perror()原型:

#include <stdio.h>
void perror(const char *msg);
它是基於errno的當前值,在標準出錯上產生一條出錯信息,然後返回。它首先輸出由msg指向的字符串,然後是一個冒號,一個空格,接著是對應於errno值的出錯信息,最後是一個換行符。

strerror()原型:

#include <string.h>
char * strerror(int errnum);
此函數將errnum(它通常就說errno值)映射為一個出錯信息字符串,並返回此字符串的指針。

VC6++測試代碼

 1 #include <stdio.h> 
 2
#include <fcntl.h> 3 #include <errno.h> 4 #include <string.h> 5 6 int main () { 7 extern int errno; 8 int fd = open("a.txt", O_RDWR); 9 if (fd == -1) 10 { 11 perror ("error1"); //perror的使用 12 printf ("errno2: %d\n", errno); //errno的使用 13 printf ("error3:%s\n",strerror(errno)); //strerror的使用 14 15 } 16 17 return 0; 18 19 }

在VC中編寫應用程序時,經常需要涉及到錯誤處理問題。許多函數調用只用TRUE和FALSE來表明函數的運行結果。一旦出現錯誤,MSDN中往往會指出請用GetLastError()函數來獲得錯誤原因。 可問題是,GetLastError()返回的只是一個雙字節數值(DWORD)。一般的調用方法為:

DWORD dw;dw = GetLastError();

【轉載++】C/C++錯誤分析errno,perror,strerror和GetLastError()函數返回的錯誤代碼的意義