Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

file

qt

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?

like image 679
nik_kgp Avatar asked Aug 26 '13 08:08

nik_kgp


People also ask

What is QFile QT?

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().

How do I copy a folder in Qt?

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.

How do I load a file in Qt?

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.


1 Answers

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.

like image 77
hyde Avatar answered Sep 19 '22 15:09

hyde