Reputation: 1122
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?
Upvotes: 9
Views: 5125
Reputation: 62817
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.
Upvotes: 5