file updating question
I need help with some file updating routines.
Lets imagine I have a file with the following contents:
john 2 5 6 7 8
guy 3 65 6 6 3 6 6
nash 3 3 5 6 666 6946
philip 3 3 6
well the file is basically a data-bank and EACH LINE is used to store some variables used in the program.
The problem is... I want to update , for example, nash.
How do I make a routine to erase curent nash data (3rd line) and replace a new 3rd line in my file? Notice that I just want to replace the 3rd line and Im not intended to change the other lines.
I've being tring several codes using fstreams i/o implements withouth results... :(
Thanks a lot,
Read in the whole file into memory(buffering the wohle file), make your changes in this buffer and write back the whole thing into your file.
that was my first decision but the file tends to grow and I can experience some problems loading the whole file into the memory thats why I must take the file line by line
Thanks a lot
You could write the data in binary mode so that you jump around the file, grab, update, and replace only the data you need
Reading into an STL container should be easy to do, any dynamic memory concerns are alleviated for you. These containers provide easy functionality to erase old and insert new data. This data can then be written back to the same file overwritting existing contents. If you don't want to use that option and you are also having issues with memory then you will probably need to do something like this:
1. Open your file for input
2. Open a second file for output
3. Read a line from the input file
a. If this is not the line you wish to replace, write it to the output file
b. If it is the line you wish to replace, then write the new line to the output file instead
c. Repeat until no more input can be read
4. Close all files
5. Delete original input file
6. Rename output file to be same name as the original input file
You can also decide that all lines beginning with a '#' say are comments, and append the new version of the record. As you read through the file line by line remember the .tellg() result for the start of each line. Then you can use seekp() and put(char) to replace the first character of the line you wish to "delete". if you change your file format slightly so that all valid lines begin with a '+' say you can even implement an undelete function. The other option would be to have only the last record count though naturally this would involve reading the entire file before the first record could be reliably accessed.
- Make each line in the file a fixed width so you can make inplace updates.
- Copy the contents of the file to a new file, while making any needed changes during the copy.
- Use the "mark record deleted, append new record" idiom that grib described.
- Use the "read it all in, make changes, write it all out" idiom that has been described.