9

我想在 C++ 中将一个文件从一个文件夹(比如驱动器 C)移动到另一个文件夹(比如驱动器 D)。如果该文件已存在于目标文件夹中,则应覆盖该文件。如何使用 C++ 标准库或 Qt 实现它?

我找到了“重命名”方法,但我不确定如果路径在不同的驱动器上它会起作用。此外,平台依赖性是什么?

4

1 回答 1

5

只需使用QFile::rename()。对于大多数目的,它应该做大约正确的事情。我认为 C++ 标准库没有文件系统间重命名调用(如果我错了,请在评论中纠正我!),std::rename只能在单个文件系统内移动。

但是,通常这里唯一(相关的)原子文件操作是在同一文件系统内重命名,其中不涉及文件内容,仅更改目录信息。我不知道支持这个的 C++ 库,所以这里是粗略的伪代码:

if basic rename succeeds
   you're done
else if not moving between file systems (or just folders for simplicity)
   rename failed
else
   try
     create temporary file name on target file system using a proper system call
     copy contents of the file to the temporary file
     rename temporary file to new name, possibly overwriting old file
     remove original file
   catch error
     remove temporary file if it exists
     rename failed

这样做可以确保新位置中的文件立即显示为整个文件,并且最坏的故障模式涉及复制文件而不是移动文件。

于 2013-08-26T10:22:14.653 回答