Usually records are added to the end of the file. How to add to the beginning?
- use the flags - sudo97
4 answers
What language do you write? To spoil the contents, as far as I understand, you can not? In this case, IMHO, just read the data from the file to the buffer, perform the necessary actions and overwrite the file.
- C ++? I'm sorry. Did not pay attention immediately. - Alexey Kotov
You read the size of your buffer at the end of the file (we read not in lines, but let's say 100KB). Those. The first read position is 100K from the end of the file.
Shift the size of the insert from the end and write the buffer. Repeat (moving to the beginning of the file), correcting the read and write positions.
When the entire file is moved, position yourself at the beginning and record your data.
When opening a file channel, you can set a parameter so that the file is not overwritten. Next, you need to put the write cursor in the desired place (see seekp ). Then write the data.
- oneJust remember, the record is "on top", the tail does not move. - avp
- Therefore, I asked about whether to spoil the content. In the method proposed by you, the beginning of the file (the area in which the data will be written) will be corrupted. Opening a file without overwriting will only leave the contents untouched at the time of opening. In addition, unless otherwise indicated by the ios :: ate flag, the cursor after opening the file is just at its beginning. - Alexey Kotov
- avp - short and clear. It is on top. - Alexey Kotov
If you write in C-style, open the file with the "w" parameter and then use fseek to set any place you want to write and write.
- Again, we return to the fact that the record will be "on top". - Alexey Kotov
- Exactly. But it seems that is exactly what is needed. - skegg
- I need no over the top - maza51
- Then, either a new file at a new location (at the end, rename it), or move it yourself. - avp
- oneThe most optimal - as has been said: read, make a new image of the file in the buffer and write it to the file from scratch. It is possible and not in the new file, but just over the old data. - skegg