Editing text file via console app
I'm trying to learn to alter a line of text within a text file via a console app. So far I can open the file, read each line into a string, identify the text I'd like to alter & alter the string. I can also set the cursor to the position of the begining of the line I want to alter. but when I write to the file it always appends instead of overwriting the line.
This is the text in the file I'm working with:
Code:
This is a text file for testing.
I plan to use it to develop my fixPath program.
I hope it works.
What I'd like to do is remove the word "fixPath from the 2nd line.
Here is the code so far:
Code:
#include <QtCore/QCoreApplication>
#include <QTextStream>
#include <QString>
#include <QFile>
int main(int argc, char *argv[])
{
QFile file("fixPath.txt");
{
while (not fileStream.atEnd())
{
str1 = fileStream.readLine();
if (str1.contains(str2))
{
str1.remove(str2);
fileStream.seek(34);
fileStream.operator<<(str1);
cout << fileStream.pos()<<endl;
}
}
file.close();
}
//return a.exec();
}
Any help is appreciated.
Ed
Re: Editing text file via console app
You need to truncate the file, rewind it and overwrite all of it. For files as we know them there is no way to cut out data from the middle of a file.