qt - 如何在我处理之前报告进度而不浏览整个文件

标签 qt qfile

我必须解析一个包含数千条记录的大文件。我想显示一个进度条,但我不知道预先记录的数量。我是否必须翻转此文件两次?

  • 第一个知道录音的数量。
  • 第二个进行治疗

或者是否有更简单的方法来获取记录数而无需在我处理之前遍历整个文件?

我的代码片段:

void readFromCSV(const QString &filename){

    int line_count=0;
    QString line;           

    QFile file(filename); 
    if(!file.open(QFile::ReadOnly | QFile::Text))
        return;

    QTextStream in(&file);

    while(!in.atEnd()){                             //First loop
        line = in.readLine();           
        line_count++;
    }

    while (!in.atEnd()) {                           //Second loop
        ...
        line = in.readLine();
        process();
        ...
    }
}

谢谢你的帮助

这个问题与这里的问题不同:counting the number of lines in a text file

1) 循环过程已经完成。在这种情况下,它是防止双重射击。

2) 代码是 QT 代码,不是作为冗余添加的 C++ 函数

最佳答案

我认为如果不至少读取一次文件就无法计算行数。为了避免这种情况,我不会依赖于行数,而是依赖于我读取了多少数据。下面是我将如何解决这个问题:

QFile file(fileName);
file.open(QFile::ReadOnly | QFile::Text);

const auto size = file.size();

QTextStream in(&file);
while (!in.atEnd()) {
  auto line = in.readLine();
  // Process line.
  // [..]

  // Calculate the progress in percent.
  auto remains = file.bytesAvailable();
  auto progress = ((size - remains) * 100) / size;
  printf("progress: %d%%\r", progress);
}

关于qt - 如何在我处理之前报告进度而不浏览整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48445170/

相关文章:

c++ - QT画圆

c++ - 如何使用 Qt 将两个 QComboBoxes 与 C++ 互连

c++ - Qt避免警告QProcess : destroyed while process still running (Assistant)

blackberry-10 - 如何在 Blackberry 10 设备中编写 QFile?

windows - 为什么我的 Qt 应用程序即使在非管理员访问权限下也会写入 protected 位置?

c++ - QFile VS ifstream。哪个更快?

c++ - 在没有原始数据的情况下重新发送 post/put 请求

c++ - Q文件/文件* : How to properly close the handle?

c++ - 如何从 QFile 中获取字节数?

c++ - Qt5,文件夹的符号链接(symbolic link)