我正在用std::errc替换boost::system::error_code。error_code支持通过error_code::message()以字符串格式显示错误消息。但我认为在STL中,我们没有一个预定义的方法来做它。我说的对吗?
如果我错了,请告诉我默认的方法,而不需要我自己写函数。如果我是对的,请帮我格式化下面程序中的错误信息(取自stackoverflow)
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
int main()
{
SetLastError((DWORD)std::errc::operation_canceled);
string str(GetLastErrorAsString());
cout << "str = " << str;
return 0;
}
输出:str =该信号量之前的所有权已经结束。rn
boost::system::error_code::message()的输出没有这些额外的".rn"。是否有办法通过调整提供给FormatMessageA()的参数,我们可以去掉这些额外的字母?或者我必须割自己(简单地去掉后面的3个字符)?如果我只是盲目地剪掉它们,有没有可能,错误信息中没有这些字符?
添加下列标志有效;
FORMAT_MESSAGE_MAX_WIDTH_MASK (0x000000FF):该函数忽略regular消息定义文本中的换行符。函数存储将消息定义文本中的硬编码换行符放入输出中缓冲区。该函数不生成新的换行符。
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
int main()
{
SetLastError((DWORD)std::errc::operation_canceled);
string str(GetLastErrorAsString());
cout << "str = " << str;
return 0;
}
我已经为你做了所有辛苦的工作:
while (size && isspace (messageBuffer[size-1]))
messageBuffer[--size] = 0;
if (size && messageBuffer[size-1] == '.')
messageBuffer[--size] = 0;