Generally speaking you need to read the old file, modify the contents in memory and write it back out again.
There are many options here, as to whether you read the file all at once, or a small piece at a time, whether you replace the existing file, etc, but this is generally the pattern to use.