PDA

View Full Version : Insert data in a text file



korwin
13th July 2011, 16:06
Hello everybody,

I am facing an issue:
I want to be able to insert some text at the end of every line of a text file.
I tried many things with QTextStream on a QFile but i am still not able to do the trick.

Initialization of a test file.
I store in the endLinePos the position of the endline character.


in_file->open(QFile::ReadWrite | QFile::Truncate);
qDebug() << "INITFILE";
QTextStream in(in_file);
for(int i=0;i<10;i++)
{
qDebug() << "INITFILE - line - "<<i;
in << "123456789\n";
endLinePos[i]=(i*10+9);
}
qDebug() << "END INITFILE";
in_file->close();




in_file->open(QFile::ReadWrite);
QTextStream in(in_file);
for(int lineNum=0; lineNum<10; lineNum++)
{
in.seek(endLinePos[lineNum]);
in<<"toto";
}


The output:


123456789toto456789toto456789toto456789toto456789t oto456789toto456789toto456789toto456789toto456789t oto


I can see that my data "toto" has been placed at the right position but it replaced the original content.
My aim would be to generate an output like


123456789toto
123456789toto
123456789toto
...


Loading the full file in the memory is not a solution: The real data are far too big (each line : 130000 char in a file having around 500 lines).


Thanks for your advices!
Korwin

meazza
13th July 2011, 16:15
.............

mcosta
13th July 2011, 16:19
You can use a new file QTemporaryFile and after completed you can copy in the old file

korwin
13th July 2011, 16:22
Hello meazza,
Unfortunatly it doesn't work.
Here is the output



123456789
123456789
123456789
123456789
123456789
123456789
123456789
123456789
123456789
123456789
totototototototototototototototototototo


If i look at the definition QIODevice::Append : The device is opened in append mode, so that all data is written to the end of the file.
It looks like normal.

Korwin

meazza
13th July 2011, 16:32
Ye realized that it wouldnt work, misunderstod what you wrote. Thats why I removed the post :)

nish
13th July 2011, 16:48
you can not insert data in between of a text file. move to sqlite for storing the data.

korwin
13th July 2011, 18:58
You are totally right and this csv export is just a temporary feature. We'll move to sql database soon.
As it is quite urgent i wont spend too much effort on this problem (already took me long time) and i will use a temporary file as suggested before.

Korwin

DanH
15th July 2011, 03:48
You can't "insert" data into a text file. You can either overwrite or append. To acheive what you want you must read the file and write a new file: Read a line, write it to the new file (but without writing the newline character), then write the new data you want and a newline. Repeat.