我必须解析一个包含数千条记录的大文件。我想显示一个进度条,但我不知道预先记录的数量。我是否必须翻转此文件两次?
- 第一个知道录音的数量。
- 第二个进行治疗
或者是否有更简单的方法来获取记录数而无需在我处理之前遍历整个文件?
我的代码片段:
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/