qt使用线程依次读取多个文件
时间: 2023-08-03 12:02:31 浏览: 38
可以使用Qt中的QThread类来实现多线程读取多个文件。下面是一个简单的示例代码:
```c++
#include <QCoreApplication>
#include <QThread>
#include <QStringList>
#include <QFile>
#include <QDebug>
class FileThread : public QThread
{
public:
FileThread(const QString& fileName) : m_fileName(fileName) {}
protected:
virtual void run()
{
QFile file(m_fileName);
if (file.open(QIODevice::ReadOnly))
{
QByteArray data = file.readAll();
qDebug() << m_fileName << "content:" << data;
file.close();
}
else
{
qDebug() << "Failed to open " << m_fileName;
}
}
private:
QString m_fileName;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QStringList fileNames;
fileNames << "file1.txt" << "file2.txt" << "file3.txt";
QList<FileThread*> threads;
foreach (const QString& fileName, fileNames)
{
FileThread* thread = new FileThread(fileName);
threads.append(thread);
thread->start();
}
foreach (FileThread* thread, threads)
{
thread->wait();
delete thread;
}
return a.exec();
}
```
上面的代码中,FileThread类继承自QThread类,用于读取单个文件。在main函数中,创建一个文件名列表,然后遍历列表,创建FileThread线程对象并启动线程。最后,等待所有线程结束并释放线程对象。注意在读取文件时要进行错误处理。
阅读全文