Update data in a CSV file
Unsolved
General and Desktop
-
Hello guys. I'm trying to open a csv file and change some data in the file.
But I can just append in bottom the file by this option (QIODevice::Append).
What's the solution to update any data from anywhere in csv file?? -
@SeyMohsenFls
Since it is a text file you cannot (or at least should not, because you probably don't understand the consequences) update (change) anything inside it. Like any text file, you need to rewrite the whole file if you want to alter something. -
@SeyMohsenFls Read the file, modify the data, write it back to file
-
@SeyMohsenFls
As stated, you have to rewrite the complete file, can't be clearer. You have two possible ways:- Read whole file into memory, in some structure (even if it's just a list of lines). Make modifications to it in memory. Write whole file back when completed, e.g. overwriting original file. This is how e.g. a text editor or
sort
works. - Open existing file for read, open a new file for write. As you read each line in, make any modifications and write new line out. At the end probably/perhaps delete original file and rename new file to that. This is how e.g.
sed
works.
Either way you completely rewrite new file. Difference is how much memory you use.
- Read whole file into memory, in some structure (even if it's just a list of lines). Make modifications to it in memory. Write whole file back when completed, e.g. overwriting original file. This is how e.g. a text editor or