C++:无法移动文件,因为文件夹名称上有空格

C++: Cannot move a file, because of a space on folder's name

本文关键字:文件夹 空格 因为 移动 文件 C++      更新时间:2023-10-16

我正在使用 movefile()将文件移至特定文件夹,但是,当我尝试这样做时,它不起作用,因为该文件夹的名称"新文件夹"中有空间但是,如果文件夹的名称没有空格,则可以工作

这是一个示例(没有文件夹,其中包含名称上的空间):

std::string input1 = "C:\Users\Username\link.txt";
std::string input2 = "C:\Users\Username\Desktop\NewFolder\link.txt";
MoveFile(input1.c_str(), input2.c_str());

有一个示例,当时有一个包含空间的文件夹

std::string input1 = "C:\Users\Username\link.txt";
std::string input2 = "C:\Users\Username\Desktop\New Folder\link.txt"; //here's the folder
MoveFile(input1.c_str(), input2.c_str());

我没有遇到任何语法错误,但是我很确定,由于" new" " folder" 之间的空间,它无效

有什么方法来修复它?

我无法再现故障。

使用我的项目配置为ANSI/MBC而不是Unicode(因此允许std::string::c_str()传递到基于TCHARMoveFile()宏),所示的确切代码(仅用我自己替换Username)对我来说很好。 MoveFile()返回true,并且文件实际移动。

std::string input1 = "C:\Users\<my username>\link.txt";
std::string input2 = "C:\Users\<my username>\Desktop\New Folder\link.txt";
MoveFile(input1.c_str(), input2.c_str()); // <-- SUCCEEDS

因此,问题必须在其他地方。两者:

  • 源文件不存在,或者是无法访问的。
  • 目的地文件夹不存在(MoveFile()不会为您创建它!使用CreateDirectory()或事先使用类似功能),或者无法访问。
  • 移动数据时存在错误。在NTFS文件系统上很少见,因为将文件从一个文件夹从一个文件夹转移到同一驱动器上的另一个文件夹只会重新放置文件引用而不移动实际文件数据。

如果 MoveFile()返回false,则需要致电GetLastError()才能找出为什么失败。