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
文件夹:)。
检查'MoveFile'的返回值,当你看到它说失败时,使用'GetLastError'找出原因。 –
根据['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()'。 –
如果这些都是目录,那么你希望发生的事情不会。 –