2012-02-08 26 views
2

我试图复制一个目录到一个新的位置。所以我使用SHFileOperation/SHFILEOPSTRUCT如下: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; 
} 

所以我设置为上述值。我在文件夹中创建了一个文件(我已经关闭了句柄,因此它应该可以移动)。 SHFileOperation调用返回2,但我无法找到解释这些错误代码的地方。有没有人知道我在哪里可以找到2意味着什么,或者有没有人有任何想法,为什么它可能不工作?干杯

回答

7

错误代码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"); 
} 

从阅读pTopFrom指定SHFileOperation字符串的文件必须是双空终止:你的只有单空终止。请尝试以下操作:

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

双空终止。所以我在每个结尾添加一个\ 0? – discodowney 2012-02-08 10:42:39

+0

基本上,是的。 – hmjd 2012-02-08 10:55:07

+0

它没有任何区别。我仍然从SHFileOperation得到2。这两个文件夹都存在,并且pFrom文件夹中有一个文件,所以我不知道它无法找到哪个文件。 – discodowney 2012-02-08 10:58:24

0

SHFileOperation函数已被IFileOperation在Windows Vista中替换。那么使用SHFileOperation很聪明吗?或者代码只能在<远景中运行。

编辑: 删除了部分内容,我误解了您的部分内容。

+0

是的香港专业教育学院使用的CopyFile但我想移动某个目录的所有文件,我知道SHFileOperation可以做到这一点只是上面的代码(或者,你知道,代码的工作版本以上)。我不知道IFileOperation。我好奇,但。如果im在Windows资源管理器中,我选择使用键盘/鼠标将文件夹复制到其他地方,是否使用此IFileOperation或SHFileOperation? – discodowney 2012-02-08 10:33:48