使用线程执行QFile::copy时,怎样停止文件的复制,我使用锁停止线程无法做到
你可以在线程中设置一个标志位,然后在复制过程中进行检查以判断该标志的值,决定是否停止复制
#include <QFile>
#include <QThread>
class CopyThread : public QThread
{
Q_OBJECT
public:
CopyThread(const QString &source, const QString &destination)
: m_source(source)
, m_destination(destination)
, m_stop(false)
{
}
void stop()
{
m_stop = true;
}
protected:
void run()
{
QFile file(m_source);
if (file.open(QIODevice::ReadOnly)) {
QFile destination(m_destination);
if (destination.open(QIODevice::WriteOnly)) {
char buffer[1024];
qint64 readBytes = 0;
while ((readBytes = file.read(buffer, 1024)) > 0 && !m_stop) {
destination.write(buffer, readBytes);
}
destination.close();
}
file.close();
}
}
private:
QString m_source;
QString m_destination;
volatile bool m_stop;
};
比如上面的代码,需要停止复制时调用 stop 函数就可以了
不知道你这个问题是否已经解决, 如果还没有解决的话:如果采用只写( WriteOnly )的方式打开文件,源文件中的内容会被覆盖。这里采用追加(Append)的方式来打开文件,再进行写操作。
//设置打开方式(追加的方式打开,然后再写)
file.open(QIODevice::Append);
file.write("实干兴邦");
file.close();