You cannot really do this without writing the whole file. You could seek to the beginning of the line and then write the new line. But first you’d have to find out the offset of that line. If you don’t already have that this means reading the file from the beginning to that line. Then you could write the new line, but only if it is exactly the same length as the original line. If it is longer it will overwrite the next line - there is no way to insert data into a file. If the new line is shorter than the old one the end of the old line will remain. The same length requirement is also tricky. This means the same length in bytes. Depending on the character encoding some characters might require more bytes than others.
If you really need to do this and have it work for about every case you’d have to use those steps:
- Read the entire file to find out the offset of the line you’re interested in
- Seek to the offset of the line
- Write the new line
- Write out the rest of the file you read in step 1.
This algorithm will work, no matter how long or short the lines are or how they are encoded. But this will probably be more expensive than just writing out the whole file, especially if you have it in memory anyways.
Have you actually verified that it is not acceptable to write out the whole file or are you doing premature optimization here? If your text file is really that big you should be considering a database, like SQLite, or to use Core Data.