2017-03-01 259 views
0

我想将test1中的所有文件复制到test2。代码编译但没有任何反应。将文件从一个目录移动到另一个目录

#include <iostream> 
#include <stdlib.h> 
#include <windows.h> 

using namespace std; 

int main() 
{ 
    string input1 = "C:\\test1\\"; 
    string input2 = "C:\\test2\\"; 
    MoveFile(input1.c_str(), input2.c_str()); 
} 

我在考虑xcopy,但它不接受预定义的字符串。有没有解决办法?

+3

检查'MoveFile'的返回值,当你看到它说失败时,使用'GetLastError'找出原因。 –

+2

根据['MoveFile()'](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365239.aspx)文档:“*'lpNewFileName' [in] 文件或目录**新名称不能存在**新文件可能位于不同的文件系统或驱动器上新的目录必须位于同一个驱动器上*“test2'目录是否已存在?考虑使用['SHFileOperation()'](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762164.aspx)或['IFileOperation'](https://msdn.microsoft.com /en-us/library/windows/desktop/bb775771.aspx)而不是'MoveFile()'。 –

+0

如果这些都是目录,那么你希望发生的事情不会。 –

回答

1
std::string GetLastErrorAsString() 
{ 
    //Get the error message, if any. 
    DWORD errorMessageID = ::GetLastError(); 
    if (errorMessageID == 0) 
     return std::string(); //No error message has been recorded 

    LPSTR messageBuffer = nullptr; 
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 
     NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); 

    std::string message(messageBuffer, size); 

    //Free the buffer. 
    LocalFree(messageBuffer); 

    return message; 
} 
int main() 
{ 
    string input1 = "C:\\test1\\"; 
    string input2 = "C:\\test2\\"; 
    if (!MoveFile(input1.c_str(), input2.c_str())) 
    { 
     string msg = GetLastErrorAsString(); 
     cout << "fail: " << msg << endl; 
    } 
    else { 
     cout << "ok" << endl; 
    } 
    system("pause"); 
} 

您的代码工作对我来说,你可能要设置的字符在你的项目属性设置为use multi-byte character set。 如果没有,请向我们提供错误。 检查您是否拥有C:上的写权限。 检查C:中是否已有test2文件夹:(或C:中没有test1文件夹:)。

+0

'GetLastErrorAsString()'在'std :: string' c'tor引发异常的情况下泄漏内存。它还很晚地调用'GetLastError()'。在[本文档主题]中已经发布了更好的实现(http://stackoverflow.com/documentation/winapi/2573/error-reporting-and-handling/9378/)。 – IInspectable

+0

此外,写入'std :: cout'可能会间接导致'GetLastError()'重置。如果MoveFile()成功,调用'GetLastError()'是没有意义的。只有当MoveFile()失败时,你必须调用GetLastError(),并且必须在调用其他Win32 API函数之前调用GetLastError(),例如:if(!MoveFile(input1.c_str(),input2.c_str()) ){string msg = GetLastErrorAsString(); cout <<“失败:”<< msg << endl; } else {cout <<“ok”<< endl; }' –

+0

@RemyLebeau谢谢你指出这一点,我用它编辑了答案 – user

0

我通过从test2删除\\解决了该问题。文件夹测试2不存在。感谢您的答复和测试代码。我认为SHFileOperation将是一个更好的选择,因为我必须将文件从软盘传输到C驱动器。 string input1 =“C:\\ test1 \\”; string input2 =“C:\\ test2”;

相关问题