how copy the content of a file somewhere in memory?

HI!
I want to change somethings in a file.
I can't just append to it, because I want to change somethings in the first and in the middle and in the last .
and I don't want rename the file, I mean the file's name should remain as it is .
for example there is a file :
(student.txt)
2

john
14523

joe
369589


I want to change it to this :
(student.txt)
3

john
14523

joe
369589

jack
9546


As you see the upper number is changed , a new person with a new ID is added .
I want to do these things in the same file .
What I have in mind is to copy all lines in a vector of strings and then erase the file content and write the vector to the file .
But I'm looking for a better and faster algorithm , because the file may sometimes be more than 1000 lines .
And I don't want to create another file first , erase this and copy that into this file.
Thanks In advance!
Last edited on
But I'm looking for a better and faster algorithm , because the file may sometimes be more than 1000 lines .

That sounds quite a moderate size, it may still be simpler to store all the data in a vector or other container.

If the filesize is truly huge, then it may be best to format the number on the first line to be of a fixed size, such as "000000003" rather than just "3". Then the value could be over-written as required without re-writing the entire file. Updating a file by processing a series of transactions such as insert/update/delete used to be a common task, but it usually requires both the file and the transactions to be sorted according to some key field. Then there is no need to hold the entire file in memory, it is just read in and written out to a new file one record at a time.
Topic archived. No new replies allowed.