I am using QT, I am not able to find out how to copy a file from one directory to another? How can I achieve this?
Asked
Active
Viewed 7.1k times
3 Answers
97
You can use QFile which provides a copy method.
QFile::copy("/path/file", "/path/copy-of-file");
-
4I think you should also specify that it returns `false` on error. Something like: `if(!QFile::copy(...)) { ...handle error... }`. In some cases an error can be ignored, in others, the process has to stop! – Alexis Wilke Apr 24 '18 at 16:43
-
Yes, I did receive an error while using QFile::copy to Move from one drive letter to another. It turned out, QFile:rename function worked for me – Manjunath Oct 24 '18 at 13:39
-
20
If destination file exist, QFile::copy
will not work. The solution is to verify if destination file exist, then delete it:
if (QFile::exists("/path/copy-of-file"))
{
QFile::remove("/path/copy-of-file");
}
QFile::copy("/path/file", "/path/copy-of-file");

Benjamin Lucidarme
- 1,648
- 1
- 23
- 39
-
4Why not just QFile::remove unconditionally? That is easier to read and faster to run. – spectras Jan 09 '21 at 18:56
-4
The following code works in windows for specified reasons. This will set the path to specified drive and create the folder you created in Under UI Mode. Then copies the file from source to destination. Here the source is installation directory contained some files which are used for plotting curves. this file are not modified by users. They just use it.
hence this works as copy from installation directory to specified folder
void MainWindow::on_pushButton_2_clicked()
{
QString str5 = ui->lineEdit->text();
QString src = "."; QString setpath;
QDir dir(src);
if(!dir.exists()){
return;
}
dir.cdUp();
//dir.cdUp();
setpath = "E://";
dir.setPath(setpath);
QString dst_path = str5 + QDir::separator() ;
dir.mkpath(dst_path);
dir.cd(dst_path);
QString filename = "gnu.plt";
QString filename2 = "Load curve.plt";
QString filename3 = "tube temp.plt";
QFile file(filename);
QFile file1(filename2);
QFile file2(filename3);
file.copy(src+QDir::separator()+filename, setpath+QDir::separator()+str5+QDir::separator()+filename);
file1.copy(src+QDir::separator()+filename2, setpath+QDir::separator()+str5+QDir::separator()+filename2);
file2.copy(src+QDir::separator()+filename3, setpath+QDir::separator()+str5+QDir::separator()+filename3);
}

Iron Man
- 13
- 1
-
1You probably need to use `QDir::separator()` when you set the `setpath` variable to `"E://"`. It looks like you meant `"\\"` also. Also your answer is way specialized for what the OP was asking. You should have simplified. Finally, you don't need to create a `QFile` object to do the copy since there is a static function. But if you do create such a QFile, then you should use the copy with one filename: `file.copy(destination);`. – Alexis Wilke Apr 24 '18 at 16:39