Open In App

How Should I Use FormatMessage() in C++?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to use the FormatMessage function properly
#include <Windows.h>
#include <iostream>
using namespace std;
  
// Function to display error message corresponding to the given error code
void DisplayErrorMessage(DWORD errorCode) {
  
    // Buffer to store the error message
    LPVOID lpMsgBuf;
  
    // Call FormatMessage function to retrieve the error message
    DWORD dwChars = FormatMessage(
        // allocate the buffer
        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                               
    );
  
    // Check if FormatMessage was successful
    if (dwChars == 0) {
        // Print error if FormatMessage was not able to get the error message
        cerr << "Failed to retrieve error message. Error code: " << GetLastError() << endl;
        return;
    }
    // Print the retrieved error message
    cout << "Error: " << reinterpret_cast<LPTSTR>(lpMsgBuf) << endl;
  
    // Free the allocated buffer
    LocalFree(lpMsgBuf);
}
  
  
int main() {
      
    DWORD errorCode = ERROR_FILE_NOT_FOUND;
  
    // Display error message corresponding to the error code
    DisplayErrorMessage(errorCode);
  
    // Return 0 to indicate successful execution
    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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads