Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c++ - Does CString preserve GetLastError code?

I need to post some debugging information into a log using MFC's CString, but I can't seem to find if it preserves error code set by the last WinAPI (and retrievable with GetLastError)?

EDIT: Here's a code example of a simplified version of what I'm currently doing in my existing project:

HANDLE hFile = CreateFile(strFilePath, ...);
if(hFile == INVALID_HANDLE_VALUE)
{
    logError(collectDebuggerInfo(strFilePath));
}

void logError(LPCTSTR pStrDesc)
{
    int nLastError = ::GetLastError();
    CString str;
    str.Format(L"LastError=%d, Description: %s", nLastError, pStrDesc);

    //Add 'str' to the logging file...
}

CString collectDebuggerInfo(LPCTSTR pFilePath)
{
    int nLastError = ::GetLastError();
    CString str;

    str.Format(L"Debugging info for file: "%s"", pFilePath);

    ::SetLastError(nLastError);
    return str;   //RETURNING CString -- will it overwrite the last error?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One convenient solution would be to define a class that contains both a CString and a last error code, then overload logError and redefine collectDebuggerInfo something like this:

void logError(StringWithEmbeddedErrorCode instr)
{
    LPCTSTR pStrDesc = instr.str;
    SetLastError(instr.nLastError);
    logError(pStrDesc);
}

StringWithEmbeddedErrorCode collectDebuggerInfo(LPCTSTR pFilePath)
{
    int nLastError = ::GetLastError();
    CString str;

    str.Format(L"Debugging info for file: "%s"", pFilePath);

    return StringWithEmbeddedErrorCode(str, nLastError);
}

This way you don't have to change the code that invokes the error handling functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...