簡體   English   中英

Qt,QFile寫入特定行

[英]Qt, QFile write on specific line

我在 Qt 中遇到了另一個問題,我似乎無法弄清楚如何使用QFile在文本文件的特定行上寫入。 取而代之的是,一開始寫的一切都被擦除。 那么根據給定的信息,我將如何寫入QFile中的特定行?

這里有兩個函數。

  1. 第一個function 搜索一個文件,然后得到兩個變量。 一個找到下一個空行,一個獲取當前 ID 號。
  2. 第二個 function 應該寫。 但是我一直在尋找我需要的文檔,我用谷歌搜索它並嘗試了很多搜索都無濟於事。

Function 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

}

上面的 function 讀取文件,看起來像這樣。

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

function 得到兩位我認為可能需要的信息。 我不太熟悉QFile和搜索,但我認為我需要這些變量:

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

所以我把那些變量傳給了下一個function,在function的最后 1. Write(x, currentID);

Function 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";
}

我沒有嘗試自己解決問題,function 所做的就是用“HelloWorld”替換文本文件的所有內容。

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

如果要插入文件的行始終是最后一行(如 function 1 所建議的那樣),您可以嘗試在 Write 方法中使用 QIODevice::Append 以 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();

上面的代碼片段將 append 文本“The magic number is: 4”放在文件末尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM