How to use GetLastError() in VC++ 2010
Making the conversion from Java to c++ isn't easy so help me guys.
i want to see if i'm getting an Access_Error violation in this code:
BOOL didThisFail = FALSE;
if (CopyFile(L"MyApplicatio开发者_运维问答n.exe", szPath, didThisFail))
cout << "File was copied" << endl;
if (CopyFileW(L"MyApplication.exe", szPath, didThisFail))
{
std::cout << "File was copied" << std::endl;
}
else if (GetLastError() == ERROR_ACCESS_DENIED)
{
std::cout << "Can't do that." << std::endl;
}
else
{
DWORD lastError = GetLastError();
//You have to cache the value of the last error here, because the call to
//operator<<(std::ostream&, const char *) may cause the last error to be set
//to something else.
std::cout << "General failure. GetLastError returned " << std::hex
<< lastError << ".";
}
There's an example on MSDN's website: http://msdn.microsoft.com/en-us/library/ms680582(v=vs.85).aspx
void ErrorExit(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
精彩评论