【问题标题】:Getting the pointer back to the first line - QFile让指针回到第一行 - QFile
【发布时间】:2013-08-25 14:34:52
【问题描述】:

从文件中读取数据并将其保存在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());
        }
    }

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

【问题讨论】:

    标签: c++ qt file qfile


    【解决方案1】:

    file.close()关闭文件

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

    while(!file.atEnd()){...} 解决问题之前重新打开它。

    【讨论】:

    • 或者您可以使用QFile::seek 将光标移动到文件的开头。
    【解决方案2】:

    重置 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”和“while”循环多。 上面的代码效率更高吗?快点?没有错误?不知道。但至少对文件操作少。 :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多