0

I have a text file which looks like this (Example):

123456789 18-5-2014
985665547 23-12-2016

I've a read/write function in a while(!file.atEnd) construction like this:

while (!file.atEnd()) 
{
    if (date-currentdate<42) {
        ui->label->setText(number); //number is the number before the date in the text file
    //Here I want the function to delete the current line
    }

}

What I want is to delete the line that is just used in the if statement from my text file. By line (as example) I mean 123456789 15-5-2014.But how do I do this?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
SjonTeflon
  • 511
  • 2
  • 12
  • 26
  • Please read this about how to detect the end of a file: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Thomas Matthews Jul 07 '14 at 18:11
  • @ThomasMatthews: I am leaning towards to reopen this as it is about *Qt*, whereas the duplicate is generic C++. Although, it should still be closed for no effort shown so far. We do not help with "gimme teh codez" questions. – lpapp Jul 07 '14 at 18:15
  • @ThomasMatthews. Interesting reference but does that also apply to the Qt framework? – RobbieE Jul 07 '14 at 18:16
  • @RobbiE: Why do you need Qt to modify a file? The process is the same: copy original data to new file until the target text line is reached. Read the deleted line (skipping it). Read remaining text and append to new file. – Thomas Matthews Jul 07 '14 at 18:32
  • You don't but the question is tagged as such and the sample code is using the function `atEnd()`, which is found in the `QIODevice` class of the framework. – RobbieE Jul 08 '14 at 08:35

1 Answers1

0

If the file can be large:

  1. Create a temporary file.
  2. While reading, write into the temp file all the lines except the one that you want to delete.
  3. Delete the original file.
  4. Rename the temporary file as the original file.

If you know that the file is always small, you can optionally do as follows:

  1. Read in memory all the lines, except the one to be deleted.
  2. Rewrite the file using the strings that you now have in memory.
Reunanen
  • 7,551
  • 2
  • 31
  • 55