How Should I Use FormatMessage() in C++?
Last Updated :
28 Apr, 2025
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.
Similar Reads
Formatted I/O in C++ C++ helps you to format the I/O operations like determining the number of digits to be displayed after the decimal point, specifying number base etc. Example: If we want to add + sign as the prefix of out output, we can use the formatting to do so: stream.setf(ios::showpos) If input=100, output will
7 min read
How to Use cin.fail() Method in C++? In C++, the cin.fail() method is a part of <iostream> library that is used to check whether the previous input operation has succeeded or not by validating the user input. In this article, we will learn how to use cin.fail() method in C++. Example: Input: Enter an integer: aOutput: Invalid Inp
2 min read
How Do I Handle Multi-Byte Characters in C++? In C++, characters are represented using the char data type, which is designed to hold a single byte. However, there are many languages other than English, and all these characters cannot be represented by a single byte. These characters are known as multi-byte characters. In this article, we will l
2 min read
How Can I Get a File Size in C++? In C++, we often need to determine the size of a file which is the number of bytes in a file. This is done for various applications, such as file processing or validation. In this article, we will learn how to get the file size in C++. Example: Input: FilePath = "C:/Users/Desktop/myFile.txt" Output:
2 min read
How to Read File into String in C++? In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++. Reading Whole File into a C++ StringTo read an entire file line by line and save it into std::string, we can use std::ifstream class to
2 min read