You largely cannot do this.
You can use fseek
to go to a specific place in the file, and you can write data to that place (you probably want to use the "r+"
mode).
But a file is usually stored as a sequence of bytes (or characters), and not as a sequence of strings.
If you carefully write down exactly the same number of bytes that were already in the string, you can probably leave with it, but in your example the lines have different lengths, so this is not an option.
You can, for example, pad each line with spaces, so that they have the same length, but then it’s easy to spoil the layout if you change the file using, say, a regular text editor.
For text files, the usual approach is to read the file into memory, change the representation in memory, and recreate the entire file. You probably want to write the contents to a new temporary file, and then rename it after you confirm that there were no write errors.
This is what text editors usually do.
(Don’t worry about efficiency, 2000 lines are not so many, and you won’t notice how long it takes to write them.)
There are alternatives. You can define a binary format with fixed records or you can use a database. Or you can simply add new lines to the file and treat duplicates as if they were deleted (but this can lead to the file being very large if you make a lot of updates).
Keith Thompson Jul 14 '12 at 22:45 2012-07-14 22:45
source share