【问题标题】:SHFileOperation/SHFILEOPSTRUCTSHFileOperation/SHFILEOPSTRUCT
【发布时间】:2012-02-08 10:22:35
【问题描述】:

我正在尝试将目录复制到新位置。所以我使用 SHFileOperation/SHFILEOPSTRUCT 如下:

SHFILEOPSTRUCT sf;
memset(&sf,0,sizeof(sf));
sf.hwnd = 0;
sf.wFunc = FO_COPY;
dirName += "\\*.*";
sf.pFrom = dirName.c_str();
string copyDir = homeDir + "\\CopyDir";
sf.pTo = copyDir.c_str();
sf.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI;

int n = SHFileOperation(&sf);
if(n != 0)
{
    int x = 0;
}

所以我设置了上面的值。我在文件夹中创建了一个文件(我已经关闭了 Handle,所以应该可以移动)。 SHFileOperation 调用返回 2,但我找不到解释这些错误代码的任何地方。有谁知道我在哪里可以找到 2 的含义,或者有人知道为什么它可能不起作用?干杯

【问题讨论】:

  • SHFileOperation 函数在 Windows Vista 中已被 IFileOperation 替换。那么使用 SHFileOperation 聪明吗?或者代码是否只在
  • 是的,我用过 CopyFile 但我想移动一个包含所有文件的目录,我知道 SHFileOperation 只需使用上面的代码就可以做到这一点(或者,你知道,使用上面代码的工作版本) .我不知道 IFileOperation。不过我很好奇。如果我在 Windows 资源管理器中并且我选择使用键盘/鼠标将文件夹复制到其他地方,它会使用这个 IFileOperation 还是 SHFileOperation?

标签: c++ windows


【解决方案1】:

错误码2表示系统找不到指定的文件。

查看Windows System Error Codes获取错误描述的完整列表,或者编写一个函数来获取错误代码的描述:

std::string error_to_string(const DWORD a_error_code)
{
    // Get the last windows error message.
    char msg_buf[1025] = { 0 };

    // Get the error message for our os code.
    if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 
                      0,
                      a_error_code,
                      0,
                      msg_buf,
                      sizeof(msg_buf) - 1,
                      0))
    {
        // Remove trailing newline character.
        char* nl_ptr = 0;
        if (0 != (nl_ptr = strchr(msg_buf, '\n')))
        {
            *nl_ptr = '\0';
        }
        if (0 != (nl_ptr = strchr(msg_buf, '\r')))
        {
            *nl_ptr = '\0';
        }

        return std::string(msg_buf);
    }

    return std::string("Failed to get error message");
}

通过阅读SHFileOperation 的文档,为pTopFrom 指定的字符串必须是双空终止:您的只是单空终止。请尝试以下操作:

dirName.append(1, '\0');
sf.pFrom = dirName.c_str();
string copyDir = homeDir + "\\CopyDir";
copyDir.append(1, '\0');
sf.pTo = copyDir.c_str();

【讨论】:

  • 双空终止。所以我在每个末尾添加一个 \0?
  • 它没有任何区别。我仍然从 SHFileOperation 获得 2。两个文件夹都存在,而且pFrom文件夹里有一个文件,所以不知道是什么文件找不到。
  • 你是如何附加额外的 NULL 终止符的?
  • 我现在有 dirName += "\*.*\0",copyDir 的相同附件
  • 这行不通,因为分配给dirName 将在第一个NULL 终止符处停止。试试我在上面的答案中添加的方法。
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 2010-12-13
  • 1970-01-01
  • 2013-06-02
  • 2012-06-07
  • 1970-01-01
  • 2015-03-01
  • 2012-06-09
相关资源
最近更新 更多