Qt 5 Copy a File

In the following example, ‘srcPath’ is the complete path of a file to be copied,
and ‘destPath’ is the complete path of the file to be copied to.

Myclass.h:

#include <QString>

class Myclass
{

public:

bool inputfilefound;

public:

void copyFile (QString srcPath, QString destPath);

};

Myclass.cpp

#include "Myclass.h";
#include <QFile>
#include <QMessageBox>
#include <QTextStream>

void Myclass::copyFile(QString srcPath, QString destPath)
{
    QMessageBox msgBox;
    QFile srcFile(srcPath);
    QFile destFile(destPath);

    inputfilefound = true;

    if (srcFile.open(QIODevice::ReadOnly | QIODevice::Text))

    {
        if (destFile.open(QIODevice::WriteOnly | QIODevice::Text))

        {

            QTextStream srcStream(&srcFile);
            QTextStream destStream(&destFile);

            while (!srcStream.atEnd())
            {

                // :NOTE: QTextStream::readLine() strips the trailing newline
                // so we are putting it back with the "\n". This may cause
                // newlines to change from "\n" to \r or similar problems depending
                // on platform. Check out QIODevice::readLine() if that is a problem

                destStream << srcStream.readLine() << endl;

            }

        destFile.close();

        }

    srcFile.close();

    }

    else {

        msgBox.setText ("Unable to find file");
        msgBox.exec();

        inputfilefound = false;

    }

}

Advertisements