Qt 打开并读取文件内容的方法

1,进程打开

QProcess p(0)

p.start(cat path/filename);

p.waitForStarted();

p.waitForFinihed();

QString str = p.readAllStandardOutput();

str = str.mid(2,8);//取第二到第八个字符


2,文件系统打开

char buf[1024] = {0};

 FILE* fp0 = fopen("path/ filename", "r+");//读写方式打开

 memset(buf, 0, sizeof(buf));

 fgets(buf, sizeof(buf), fp0);

 QString str = buf;

 str = str.mid(2,8);

 fclose(fp0);

 fp0 = NULL;

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt中,可以使用`QThread`类来创建一个新线程,然后在新线程中读取文件内容。具体步骤如下: 1. 创建一个继承自`QThread`的子类,例如`FileReaderThread`。 2. 在子类中重载`run()`函数,该函数中实现文件读取的逻辑。 ```c++ void FileReaderThread::run() { QFile file(m_filePath); if (file.open(QIODevice::ReadOnly)) { QByteArray data = file.readAll(); emit fileContentReady(data); file.close(); } } ``` 在上面的代码中,我们首先打开文件,然后读取文件内容到`QByteArray`中,并通过信号`fileContentReady`将读取到的数据发送到主线程。 3. 在主线程中创建一个`FileReaderThread`的实例,并连接`fileContentReady`信号到槽函数。 ```c++ FileReaderThread* fileReaderThread = new FileReaderThread(filePath, this); connect(fileReaderThread, SIGNAL(fileContentReady(QByteArray)), this, SLOT(onFileContentReady(QByteArray))); fileReaderThread->start(); ``` 4. 在槽函数`onFileContentReady()`中处理读取到的文件内容,例如:更新UI界面或者进行其他操作。 ```c++ void MainWindow::onFileContentReady(QByteArray data) { ui->textEdit->setText(QString(data)); } ``` 在上述代码中,我们首先创建了一个`FileReaderThread`的实例,并连接了`fileContentReady`信号到槽函数`onFileContentReady()`。然后我们调用`start()`函数来启动新线程,并在`onFileContentReady()`函数中处理读取到的文件内容。 注意:上述代码仅为示例,具体实现方式还需要根据你的具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值