c++ - 尝试使用带有 C++ 的 MoveFile 移动文件时出现 ERROR_INVALID_NAME

标签 c++ windows winapi io

        wstring path = L"C:\\Users\\oneworduser\\Desktop\\trash";
        LPCWSTR origin = (path + L"\\" + files.at(i)).wstring::c_str();
        LPCWSTR destination = (path + L"\\" + extensions.at(i) + L"\\" + files.at(i)).wstring::c_str();
        //move file
        BOOL b = MoveFileW(origin, destination);

MoveFileW 返回 false。
files.at(i) 是当前文件的 wstring 名称。
extensions.at(i) 是在 .在 files.at(i) 中。例如:
如果 files.at(0)mytext.txt,则 extensions.at(0)txt。 MoveFileW 返回 false,如果我 GetLastError(),我会收到错误 123,即 ERROR_INVALID_NAME
为什么我不能移动文件?

最佳答案

你有未定义的行为。 std::wstring::operator+ 正在返回一个临时值,origindestination 最终指向释放的内存。如果您在调试器中查看过您的程序,您几乎肯定会看到这一点。

将您的代码更改为:

wstring path = L"C:\\Users\\oneworduser\\Desktop\\trash";
wstring origin = path + L"\\" + files.at(i);
wstring destination = path + L"\\" + extensions.at(i) + L"\\" + files.at(i);
//move file
BOOL b = MoveFileW(origin.c_str(), destination.c_str());

关于c++ - 尝试使用带有 C++ 的 MoveFile 移动文件时出现 ERROR_INVALID_NAME,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38471674/

相关文章:

c++ - 有符号整数到无符号整数并返回?

c - 如何在 C 中使用 printf 为文本添加下划线

linux - 在 Ubuntu Linux 中使用 C/C++ 编程

c++ - 确保内存映射页在内存中

c++ - 从 C/C++ 控制 Firefox

c++ - 有没有办法重用 valgrind 抑制文件?

c++ - 使标准控制台出现在快板中

windows - 为什么 Perl 不能在 Windows 下启动 telnet?

windows - 在 Putty 中的 Screen 中将 alt-tab 传递给 Emacs

c++ - 用 C++ 显示 latex 字符串