Windows API 编程----将错误代码转换成错误描述信息

 

  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!
";
        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);
}

测试结果:

原文地址:https://www.cnblogs.com/dongling/p/5563288.html