Windows API 編程----將錯誤碼轉換成錯誤描述資訊

來源:互聯網
上載者:User

標籤:

 

  Windows編程有時會因為調用函數而產生錯誤,調用GetLastError()函數可以得到錯誤碼。如果錯誤碼為0,說明沒有錯誤;如果錯誤碼不為0,則說明存在錯誤。

  而錯誤碼不方便編程人員或使用者直觀理解到底發生了什麼錯誤。Visual Studio 2015(或之前的版本)提供了“錯誤尋找”的外部工具,輸入錯誤碼即可以查看到底發生了什麼錯誤。

  

  

 

  如果想在程式碼中查看錯誤碼對應的錯誤資訊,可以編寫如下函數來實現:

#include<iostream>#include<Windows.h>using namespace std;void winerr( );int main(int argc, char* argv[]){    system("haha");    winerr();    system("pause");    return 0;}void winerr( ){    char* win_msg = NULL;    DWORD code = GetLastError();    if (code == 0)    {        cout << "error "<<code<<":No error!\n";        return;    }            else    {        //擷取錯誤資訊        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&win_msg, 0, NULL);        if (win_msg != NULL)        {            cout << "error " << code <<":" << win_msg << endl;            LocalFree(win_msg);        }    }    //為了使得該函數的調用不影響後續函數調用GetLastError()函數的結果    SetLastError(code);}

 

測試結果:

Windows API 編程----將錯誤碼轉換成錯誤描述資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.