JPGygax68
4/26/2013 - 12:39 PM

Retrieve the text associated with a Windows error code, and return it as a std::string

Retrieve the text associated with a Windows error code, and return it as a std::string

static const std::string
getWindowsErrorString(int err = 0)
{
    LPSTR s;

    if (err == 0) err = GetLastError();
    
    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        err,
        0,
        (LPSTR)&s,
        0,
        NULL) != 0)
    {
        LPSTR p = strchr(s, '\r');
        if (p) *p = '\0';
        std::string res = s;
        LocalFree(s);
        return res;
    }
    else {
        return std::string("(Failed to retrieve error string");
    }
}