PDA

View Full Version : Prepending to file



tom989
1st December 2012, 22:02
How can I add some chars to a the beginning of an existing file without overwriting (and without copying the entire file and creating a new one!)?

Thanks!

amleto
1st December 2012, 22:50
you dont.


.........

tom989
1st December 2012, 23:34
You mean "can't"!

ChrisW67
3rd December 2012, 03:58
Yes, he means cannot. For practical purposes this is un-possible ;) This is nothing to do with Qt. Rather, it is a basic limitation of the high-level concept of a sequential computer file.

With random access to the file you could try to fake it by:

extending the file by n bytes,
copying each successive block (starting at the end) along by n bytes to free n bytes at the front, then
put n extra bytes at the front of the file.

You don't save on I/O and it isn't efficient (you copy the entire file and seek a lot), but you don't need two copies of the file to exist side-by-side.

I expect a different solution to your unstated problem is a better choice.

wysota
3rd December 2012, 09:38
copying each successive block (starting at the end) along by n bytes to free n bytes at the front, then

Ouch :) That's a beautiful case of ignoring things like caches.

I'm guessing rewriting the whole file would be way faster. One can read an existing block of data, store it in memory (or in a separate file), write new content, read another block, write the previously saved block, etc. And of course one needs to keep his fingers crossed that no power failure takes place.

anda_skoa
3rd December 2012, 09:51
And of course one needs to keep his fingers crossed that no power failure takes place.

Right :)
If data integrity is important the only safe way is to write into a second file and then rename it to the orignal name. On good operating systems the rename is an atomic operation, so there is either the old file or the new file.

Someone at KDE is working on a class for Qt5 that does that internally (Window's rename isn't atomic, the class needs some other code path there).

Cheers,
_

wysota
3rd December 2012, 09:54
Right :)
If data integrity is important the only safe way is to write into a second file and then rename it to the orignal name. On good operating systems the rename is an atomic operation, so there is either the old file or the new file.

Someone at KDE is working on a class for Qt5 that does that internally (Window's rename isn't atomic, the class needs some other code path there).


Would be nice if a file cloning facility became available too. There are low-level calls in some of filesystems that allow an atomic clone of a file.