Home > Net >  How to delete a line from a txt file in Qt?
How to delete a line from a txt file in Qt?

Time:11-10

My txt file (CopyBook.txt) contains for example 10 lines. I want to delete the third one.

I have this code:

QString fname = "C://Users//Tomahawk//Desktop//copy//CopyBook.txt";
QFile file(fname);

if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
{
    QTextStream edit(&file);
    QString line;

    int reachForLine = 0;
    int neededLine = 3;

    while (reachForPage != pageCounter)
    {
        line = edit.readLine();
        reachForPage  ;
    }
}

So you can see I use "while" to reach for the line i want to delete. But I haven't found any method in Qt that allows me to do it. In future I want to use the ability of deleting lines to replace them with another ones. So how do I delete it?

CodePudding user response:

One way to do it would be to read all of the lines into a QStringList, modify the QStringList, and then turn around and write its contents back to the file again, like this:

int main(int argc, char ** argv)
{
   const QString fname = "C:/Users/Tomahawk/Desktop/copy/CopyBook.txt";
   QStringList lines;

   // Read lines of text from the file into the QStringList
   {
      QFile inputFile(fname);
      if (inputFile.open(QIODevice::ReadOnly | QIODevice::Text))
      {
         QTextStream edit(&inputFile);
         while (!edit.atEnd()) lines.push_back(edit.readLine());
      }
      inputFile.close();
   }

   // Delete the third line from the QStringList
   if (lines.length() > 2) lines.removeAt(2);  // 0==first line, 1==second line, etc

   // Write the text in the QStringList back to the file
   {
      QFile outputFile(fname);
      if (outputFile.open(QIODevice::WriteOnly | QIODevice::Text))
      {
         QTextStream edit(&outputFile);
         for (int i=0; i<lines.size(); i  ) edit << lines[i] << Qt::endl;
      }
      outputFile.close();
   }

   return 0;
}

You could also perform any replacements/insertions you want to make on the QStringList object, before writing it back to the file.

Note that this approach does use up RAM proportional to the size of the file, so for very large files (e.g. gigabytes long) you would probably want to use the create-a-second-file-and-then-rename approach proposed by @TedLyngmo in his comment, instead. For small files, OTOH, buffering in RAM is somewhat easier and less error-prone.

  •  Tags:  
  • c qt
  • Related