37
votes

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?

3
Have you tried anything at least? - Nadeem_MK
i tried with QFile::copy() method. Now it works. Thanks. - joki

3 Answers

90
votes

You can use QFile which provides a copy method.

QFile::copy("/path/file", "/path/copy-of-file");
16
votes

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");
-4
votes

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);
}