PDA

View Full Version : how can i clear a file?



Vincenzo
18th January 2009, 00:33
Hi,
How can I clear content of a file?!
For example a write to file.dat string ("how are you doing?"), after that i seek it in to begining, then i write some shorter string ("hello"), after that i get in file.dat something like: "hellore you doing?"
I checked the documentation of qt, but i don't understand very well to english, also tried a many version of potential code, but nothing worked for me :(

Further i'm interested of delete of some interval/distance of content of a file, for example if I want delete

from the (quint64) 10 to (quint64) 220
from (quint64) 10 to end of line?


Sorry for that stupid questions, but i played with it a long time without any succes. :( - also sorry for my english!

radek.z
18th January 2009, 10:35
Hi,
I guess u use something like this:
QFile file("file.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);

if you want to clear content of file.dat u should creat QDataStream object with open mode like this
QDataStream in(&file, QIODevice::Truncate);

This should help

Radek

wysota
18th January 2009, 11:05
Let's make something clear first - you can't "remove" some part in the middle of a file, you can only overwrite or truncate it. The former you do with just calling write() with new data and the latter with using QFile::resize(). So in your situation, you can either reopen the file in truncate mode:

QFile file("...");
file.open(QFile::WriteOnly|QFile::Truncate);

or resize the file after writing the new contents:

file.write("new contents");
file.resize(file.pos());

Note that this is nothing specific to Qt - files are meant to work like that.