How Should I Use FormatMessage() in C++?
Last Updated :
29 Feb, 2024
In C++, the FormatMessage() is a function used for formatting error messages returned by the system that is particularly useful for retrieving system error messages and converting them into a user-readable format. In this article, we will learn how we should use the FormatMessage function properly in C++.
Usage of FormatMessage() in C++
To use the FormatMessage() function properly in C++, we must be familiar with its syntax. Following is the syntax for the FormatMessage() function in C++:
Syntax to Use FormatMessage() in C++
DWORD FormatMessage(
[in] DWORD dwFlags,
[in, optional] LPCVOID lpSource,
[in] DWORD dwMessageId,
[in] DWORD dwLanguageId,
[out] LPTSTR lpBuffer,
[in] DWORD nSize,
[in, optional] va_list *Arguments
);
The FormatMessage() function takes the following arguments :
- dwFlags: Flags controlling formatting behavior (e.g., allocating memory, specifying language).
- lpSource: Pointer to the message source (resource file, buffer, or null for system messages).
- dwMessageId: The message identifier (often an error code).
- dwLanguageId: The desired language identifier (optional).
- lpBuffer: Pointer to the output buffer for the formatted message.
- nSize: Size of the output buffer in characters.
- Arguments: Optional array of values to insert into placeholders.
The FormatMessage() function returns the number of characters written to the buffer if successful. If the function fails it returns zero.
C++ Program to Show the Use of FormatMessage()
The below example demonstrates the use of FormatMessage() function properly to handle error messages to ensure that the users get informative error messages in case of any failures.
C++
#include <Windows.h>
#include <iostream>
using namespace std;
void DisplayErrorMessage( DWORD errorCode) {
LPVOID lpMsgBuf;
DWORD dwChars = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast < LPTSTR >(&lpMsgBuf),
0,
nullptr
);
if (dwChars == 0) {
cerr << "Failed to retrieve error message. Error code: " << GetLastError() << endl;
return ;
}
cout << "Error: " << reinterpret_cast < LPTSTR >(lpMsgBuf) << endl;
LocalFree(lpMsgBuf);
}
int main() {
DWORD errorCode = ERROR_FILE_NOT_FOUND;
DisplayErrorMessage(errorCode);
return 0;
}
|
Output
Error: The system cannot find the file specified.
Time Complexity: O(1)
Auxiliary Space: O(M) where M is the size of the buffer.
Share your thoughts in the comments
Please Login to comment...