Reputation: 1093
I am reading a QFile with QTextStream.
QFile file("example.txt");
QTextStream in(&file);
QString line = in.readLine();
while (!line.isNull()) {
if(line.contains("DELETE"))
{
// delete line
}
line = in.readLine();
}
Is there a way to delete a line ?
Upvotes: 1
Views: 13643
Reputation: 12931
You can open your file, read the contents, modify the contents, and then write them back to the file. Here is one way to do this:
QFile f("myfile.txt");
if(f.open(QIODevice::ReadWrite | QIODevice::Text))
{
QString s;
QTextStream t(&f);
while(!t.atEnd())
{
QString line = t.readLine();
if(!line.contains("DELETE"))
s.append(line + "\n");
}
f.resize(0);
t << s;
f.close();
}
Upvotes: 6
Reputation: 8313
delete a line means shift of all the rest backward.
simplest way is to write back lines in new place after first deletion.
Using temp file, and rename it to the original if success, is the safest way.
but you never write more then you read so it suppose to be OK to work on the same file.
you need to keep read pos and write pos.
it should be something like this: (based on the original code)
QFile file("example.txt");
QTextStream in(&file,QIODevice::ReadWrite);
QString line = in.readLine();
qint64 rpos,wpos=0;
bool shift = false;
while (!line.isNull()) {
rpos = in.pos();
if(!line.contains("DELETE"))
{
if(shift){
in.seek(wpos);
in<<line<<endl;
wpos = in.pos();
in.seek(rpos);
} else{
wpos = rpos;
}
}else{
shift = true;
}
in.seek(rpos);
line = in.readLine();
}
file.resize(wpos);
Upvotes: 0
Reputation: 1
As far as i know, it's not simple as that. The best solution i can think about is to the read the whole file line-by-line, push every line into a QVector, then modify the container's elements as you want, then push it back to the file.
Upvotes: 0