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?
QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream. The file name is usually passed in the constructor, but it can be set at any time using setFileName().
Once the file is chosen, its full path then appears on the line edit element. You can then copy this path and change the filename and press the 'Copy' button. Now when you check the folder, you should see the new copied file in this directory. This file should have the same exact contents as the original file.
For the loading feature, we also obtain fileName using QFileDialog::getOpenFileName(). This function, the counterpart to QFileDialog::getSaveFileName(), also pops up the modal file dialog and allows the user to enter a file name or select any existing . abk file to load it into the address book.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With