【问题标题】:How to use GetLastError() in VC++ 2010如何在 VC++ 2010 中使用 GetLastError()
【发布时间】:2011-05-28 21:10:39
【问题描述】:

从 Java 到 c++ 的转换并不容易,请帮帮我。

我想看看我是否在这段代码中遇到了 Access_Error 违规:

BOOL didThisFail = FALSE;

if (CopyFile(L"MyApplication.exe", szPath, didThisFail))
    cout << "File was copied" << endl;

【问题讨论】:

  • szPath 有问题。显示声明和初始化它的代码。
  • 汉斯你是对的。 szPath 只是一个路径 (c:\project) 而不是 c:\project\something.exe

标签: c++ visual-c++ error-handling


【解决方案1】:
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 << ".";
}

【讨论】:

  • 工作..我得到“不能这样做”,但我不知道为什么..我没有复制到一个特殊的文件夹
  • @Malfist:OP 专门要求一种错误。如果您想接收系统定义的错误字符串,您可以使用 FormatMessage API,就像 here 所做的那样。
  • @Tom:检查源和目标上的 DACL。检查以确保目标不是只读的。否则我没有太多建议。请记住,除非您的应用程序以提升的方式运行,否则它的权限会比其他情况下要弱得多。
  • 大声笑比利问题是我试图复制路径而不是 szPath\\something.exe
【解决方案2】:

在 MSDN 的网站上有一个例子: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); 
}

【讨论】:

  • 来自 MSDN,“调用线程执行的函数通过调用 SetLastError 函数来设置这个值。当函数的返回值表明这样的调用将返回有用的数据时,您应该立即调用 GetLastError 函数。那是因为某些函数在成功时调用 SetLastError 时返回零,从而消除了由最近失败的函数设置的错误代码。” msdn.microsoft.com/en-us/library/ms679360(v=vs.85).aspx
  • @Malfist:是的,有些函数可以做到这一点。但这并不意味着它可以从另一个线程完成。
  • @Malfist:这并没有使GetLastError() 比其他任何事情都更不可靠。这些函数不会被神奇地调用。它们会被你做的事情调用。所以在你打电话给GetLastError()之前不要这样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 2023-03-11
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
相关资源
最近更新 更多