使用 FormatMessage 将 GetLastError 返回值转换为文字
源码如下:
1 #include <stdio.h> 2 //#include <tchar.h> 3 #include <Windows.h> 4 5 6 7 void fmtMsg() 8 { 9 LPTSTR errorText = NULL; 10 11 FormatMessage( 12 // use system message tables to retrieve error text 13 FORMAT_MESSAGE_FROM_SYSTEM 14 // allocate buffer on local heap for error text 15 | FORMAT_MESSAGE_ALLOCATE_BUFFER 16 // Important! will fail otherwise, since we're not 17 // (and CANNOT) pass insertion parameters 18 | FORMAT_MESSAGE_IGNORE_INSERTS, 19 NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM 20 GetLastError(), 21 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 22 (LPTSTR)&errorText, // output 23 0, // minimum size for output buffer 24 NULL); 25 26 if (errorText != NULL) 27 { 28 printf_s("%s", errorText); 29 30 // release memory allocated by FormatMessage() 31 LocalFree(errorText); 32 errorText = NULL; 33 } 34 } 35 36 int main() 37 { 38 fmtMsg(); 39 40 return 0; 41 }
出处:https://stackoverflow.com/questions/455434/how-should-i-use-formatmessage-properly-in-c