将指针返回到第一行-QFile

Getting the pointer back to the first line - QFile

本文关键字:一行 -QFile 指针 返回      更新时间:2023-10-16

从文件中读取数据并将其保存在QHash中,如下所示:

 QHash<int, QVector<float> >

我的数据文件不包含头,所以当我第一次创建向量,然后进入文件循环时,我会错过第一行的数据。我的来源是:

    QFile file("...\a.csv");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(0, "Error", file.errorString());
    }
    QString fileLine = file.readLine();
    QStringList fileLineSplit = fileLine.split(',');
    hashKeySize = fileLineSplit.size();
    for(int t=0; t<hashKeySize; t++)
    {
        QVector<float> vec;
        hash_notClustered[t] = vec;
    }
    while(!file.atEnd())
    {
        QString line = file.readLine();
        QStringList list = line.split(',');
        for(int t = 0; t<list.size(); t++)
        {
            hash_notClustered[t].push_back(list[t].toFloat());
        }
    }

Q: 当使用while(!file.atEnd())循环时,如何使指针返回到第一行以避免错过第一行?

使用file.close() 关闭文件

for(int t=0; t<hashKeySize; t++)
    {
        QVector<float> vec;
        hash_notClustered[t] = vec;
    }

并且在CCD_ 3解决问题之前重新打开它。

重置QFile是一种方法。可能还有其他人。看看这个代码:
    QFile file("...\a.csv");
    if(!file.open(QIODevice::ReadOnly)){
        QMessageBox::warning(0, "Error", file.errorString());
    }
    QString fileLine = file.readLine();
    QStringList fileLineSplit = fileLine.split(',');
    int hashKeySize = fileLineSplit.size();
    for(int t=0; t<hashKeySize; t++){
        QVector<float> vec;
        hash_notClustered[t] = vec;
    }
    do{
        for(int t = 0; t<fileLineSplit.size(); t++){
            hash_notClustered[t].push_back(list[t].toFloat());
        }
        fileLine      = file.readLine();
        fileLineSplit = fileLine.split(',');
    }while(!fileLine.isEmpty());

C++的循环比"for"answers"while"循环多。上面的代码更有效率吗?更快?没有Bug?不知道。但至少在文件操作上更少。:-)