how to write content in a Specific position in a File

Abhishek Choudhary picture Abhishek Choudhary · Apr 26, 2011 · Viewed 31.4k times · Source

Suppose I have a file named abhishek.txt and that contains the following line

I am , and what is your name.

Now I want to write

Abhishek

after "I am" like I am Abhishek, .. How to write the content in this specific position directly.

Answer

Jon Skeet picture Jon Skeet · Apr 26, 2011

You can't insert data into a file... file systems (in general) simply don't support such an operation. Typically you'd open one file for reading and another for writing, copy the first part of the file from one stream to the other, write the extra part, then copy the second part of the file.

If you're trying to replace the original file, you'd then need to delete it and move the new file into place.

Sometimes it may be simpler to read the whole file into memory in one go - it depends on exactly what you're trying to do, and how big the file is.