Qt、QFile 写入特定行

Gab*_*iel 3 c++ qt qfile

我在 Qt 中遇到了另一个问题,我似乎无法弄清楚如何在带有QFile. 相反,一切都在开始时被擦除。那么根据给定的信息,我将如何写入特定行QFile

这里有两个函数。

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

功能一


    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

}
Run Code Online (Sandbox Code Playgroud)

上面的函数读取文件,看起来像这样。

1001;James;Bark
1002;Jeremy;Parker
1003;Seinfeld;Parker
1004;Sigfried;FonStein
1005;Rabbun;Hassan
1006;Jenniffer;Jones
1007;Agent;Smith
1008;Mister;Anderson
Run Code Online (Sandbox Code Playgroud)

该函数获取了我认为可能需要的两位信息。我不太熟悉QFile和搜索,但我认为我需要这些变量:

int x;  //This becomes 9 at the end of the search.
QString currentID; //This becomes 1008 at the end of the search.
Run Code Online (Sandbox Code Playgroud)

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

功能二


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";
}
Run Code Online (Sandbox Code Playgroud)

我没有尝试自己解决问题,这个函数所做的就是用“HelloWorld”替换文本文件的所有内容。

有谁知道如何在特定行上写,或者至少到文件末尾然后写?

Gia*_*uca 5

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

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