我想将文件从文件夹(例如在驱动器C上)移动到C++中的另一个文件夹(例如在驱动器D上).如果该文件已存在于目标文件夹中,则应覆盖该文件.如何使用C++ std库或Qt实现它?
我找到了"重命名"方法,但我不确定如果路径在不同的驱动器上它会起作用.而且,平台依赖是什么?
只需使用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
Run Code Online (Sandbox Code Playgroud)
这样做可以确保新位置的文件一次显示整个文件,最差的故障模式包括复制文件而不是移动.