PDA

View Full Version : writing file with QTextStream



Raul
31st May 2010, 08:23
I' using QTextStream class to write file which has already existed some texts.
and now,I want to replace the first line only.eg:
hey! //first line
wellcome to Qt's world! //second line
I want using "hello!" to replace "hey!". my code is
QFile file("/home/drcom.conf");
file.open(QFile::WriteOnly);
QTextStream out(&file);
out<<"hello!"<<endl;
the result is:
hello!
but what I want to achieve is:
hello!
wellcome to Qt's world!
the problem is the second line is cleared.how can I implement it ?if someone can tell me?thanks!

high_flyer
31st May 2010, 09:04
If it is only the first line you want to change, then all you have to do is add QIODevice::Append when you open the file, and your code will work as it is.
But this is not a very nice way of doing it, and is very unflexible.
It will not work as soon as the word you want to replace is longer then the word you want to replace it with, and/or if the position of the replaced word is not 0.
The more general way would be to seek() the wanted location, and replace the string you want to replace, making sure that the current word on that location is fully deleted.
Getting to the correct location can be done in various ways, which one is best suited for you case depends on your requirements.

Raul
31st May 2010, 14:30
if you can tell me that how to use seek() function in detail? It will be best if you take my code for example.

high_flyer
31st May 2010, 14:46
its all there in the documentation.
http://doc.trolltech.com/4.6/qtextstream.html#seek