Qt,Q文件写入特定行

Qt, QFile write on specific line

本文关键字:文件 Qt      更新时间:2023-10-16

我在Qt中遇到了另一个问题,我似乎不知道如何用QFile在文本文件的特定行上书写。相反,所有的东西都在一开始就被抹去了。那么,对于给定的信息,我将如何在QFile中写入特定的行呢?

这里有两个函数。

  1. 第一个函数搜索一个文件,然后得到两个变量。一个查找下一个空行的,一个获取当前ID号的
  2. 第二个函数应该是写的。但我一直在寻找我需要的文件,我在谷歌上搜索了它,并尝试了多次搜索,但都无济于事

功能1


    QString fileName = "C:\Users\Gabe\SeniorProj\Students.txt";
    QFile mFile(fileName);
    QTextStream stream(&mFile);
    QString line;
    int x = 1; //this counts how many lines there are inside the text file
    QString currentID;
    if(!mFile.open(QFile::ReadOnly | QFile::Text)){
        qDebug() << "Could not open file for reading";
        return;
    }
    do {
        line = stream.readLine();
        QStringList parts = line.split(";", QString::KeepEmptyParts);
        if (parts.length() == 3) {
            QString id        = parts[0];
            QString firstName = parts[1];
            QString lastName  = parts[2];
            x++; //this counts how many lines there are inside the text file
            currentID = parts[0];//current ID number
        }
    }while (!line.isNull());
    mFile.flush();
    mFile.close();
    Write(x, currentID); //calls function to operate on file
}

上面的函数读取的文件如下所示。

1001;James;Bark
1002;Jeremy;Parker
1003;Seinfeld;Parker
1004;Sigfried;FonStein
1005;Rabbun;Hassan
1006;Jenniffer;Jones
1007;Agent;Smith
1008;Mister;Anderson

这个函数得到了两个我认为可能需要的信息。我不太熟悉QFile和搜索,但我想我需要这些变量:

int x;  //This becomes 9 at the end of the search.
QString currentID; //This becomes 1008 at the end of the search.

所以我把这些变量传递给下一个函数,在函数1的末尾。Write(x, currentID);

功能2


void StudentAddClass::Write(int currentLine, QString idNum){
    QString fileName = "C:\Users\Gabe\SeniorProj\Students.txt";
    QFile mFile(fileName);
    QTextStream stream(&mFile);
    QString line;
    if(!mFile.open(QFile::WriteOnly | QFile::Text)){
        qDebug() << "Could not open file for writing";
        return;
    }
    QTextStream out(&mFile);
    out << "HelloWorld";
}

我已经省去了自己修复这个问题的任何尝试,这个函数所做的只是用"HelloWorld"替换文本文件的所有内容。

有人知道如何在特定的行上写吗,或者至少到文件的末尾再写吗?

如果要插入文件的行始终是最后一行(如函数1所示),则可以尝试在Write方法中使用QIODevice::append以追加模式打开文件。

如果你想在文件中间插入一行,我想一个简单的方法是使用一个临时文件(或者,如果可能的话,将行加载到QList中,插入行并将列表写回文件)

    QString fileName = "student.txt";
    QFile mFile(fileName);
    if(!mFile.open(QFile::Append | QFile::Text)){
        qDebug() << "Could not open file for writing";
        return 0;
    }
    QTextStream out(&mFile);
    out << "The magic number is: " << 4 << "n";
    mFile.close();

上面的代码片段将在文件末尾附加文本"神奇的数字是:4"。