C++ 使用 GetLastError 获取错误信息并使用 qDebug 输出
#include <Windows.h>
#include
int main() { // 调用一个不存在的函数,会产生错误 CreateFile('nonexistent_file.txt', GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
// 获取错误码
DWORD error = GetLastError();
// 获取错误信息
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
// 输出错误信息
qDebug() << 'Error code: ' << error;
qDebug() << 'Error message: ' << QString::fromWCharArray((LPCTSTR)lpMsgBuf);
// 释放内存
LocalFree(lpMsgBuf);
return 0;
}
输出结果:
Error code: 2 Error message: The system cannot find the file specified.
原文地址: https://www.cveoy.top/t/topic/nDd4 著作权归作者所有。请勿转载和采集!