How to write without overwrite in QFile
-
wrote on 5 Oct 2015, 13:36 last edited by
Hi
My file "myfile.txt" contain the word "world" and i want to insert at beginning of my file "Hello " so that at the end my file contain exactly "Hello world"Here is my code
QFile infile("myfile.txt");
if(infile.open(QIODevice::ReadWrite)) { QTextStream t(&infile); t.seek(0); t<<"Hello "; infile.close(); }
But the problem is that this code overwrite in "myfile.txt" and "myfile.txt" contain at end "Hello ".
How can i solve it?Thanks.
-
wrote on 5 Oct 2015, 13:39 last edited by
I don't think there is a way to prepend data in a file. You can add
"world"
to a file containing"Hello "
but not the other way around. You'll have to create a new file, dump what you want and then append what is contained in your original file. -
wrote on 5 Oct 2015, 14:04 last edited by
Well I would not create a new file. You can create a buffer in memory, write "Hello " in the buffer, stream the file in your buffer and write it back to disk.
But for very large files you need a second file cause your memory consumption would grow too high.
Besides this it is not a good approach. Prepending/Inserting data in a file is very time consuming and inefficient. Appending the data at the end of a file is much faster.Cheers
AlexRoot -
wrote on 5 Oct 2015, 15:08 last edited by
Hi, That is not strange, but perfect valid as to file storage related issue. Think about it, what will happen with other data on the disk if you just prepend data to a file and the end of the file is shifted backwards. How is your program able to detect other files behind the file you're prepending??? It can't. The OS must do that, but won't. As said before, create a second 'store' file and use two file opens to open up the files. Use the streams to swap data from the first to the second file and prepend/append data where needed.
If the files are extreme in size, you might want to consider multithreading or the QThreadpool. -
Well I would not create a new file. You can create a buffer in memory, write "Hello " in the buffer, stream the file in your buffer and write it back to disk.
But for very large files you need a second file cause your memory consumption would grow too high.
Besides this it is not a good approach. Prepending/Inserting data in a file is very time consuming and inefficient. Appending the data at the end of a file is much faster.Cheers
AlexRoot -
wrote on 5 Oct 2015, 16:29 last edited by
Here is the code:
QFile file("testfile"); if(file.open(QIODevice::ReadWrite | QIODevice::Text)) { QByteArray buf("Hello "); buf += file.readAll(); file.seek(0); file.write(buf); } else qDebug() << "error reading file";
BUT it's not truncating the old content so the new content have to be bigger than the old one. If your second content could be smaller, just take the approach with a second file...
Why don't you just append it to the end of the file?Cheers
AlexRoot
4/6