简体   繁体   中英

Qt C++: Moving a file, source and destination paths are on different drives

I want to move a file from a folder (say on Drive C) to another folder (say on Drive D) in C++. If, the file is already present in the destination folder, it should overwrite that. How can I achieve it with C++ std libraries or Qt?

I found "rename" method, but I'm not sure that it will work if paths are on different drives. Moreover, what is the platform dependency?

Just use QFile::rename() . It should do approximately the right thing, for most purposes. C++ standard library does not have a inter-filesystem rename call I think (please correct me in comments if I am wrong!), std::rename can only do move inside single filesystem.

However, normally the only (relevant) atomic file operation here is rename within same file system, where file contents are not touched, only directory information changes. I'm not aware of a C++ library which supports this, so here's rough pseudocode:

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

Doing it like this ensures, that file in new location appears are a whole file at once, and worst failure modes involve copying the file instead of moving.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM