What you are attempting is an extremely bad idea.
A much better general procedure is:
- open the input file
- make a new output file
- when you are finished, rename the orignal file to .bak or whatever and then rename the new file to the original name.
File system operations are complex and there is possibility when your program "bombs" or other errors happen and you will be left in an "unrecoverable situation" - the original data has been screwed up and there is maybe even no way, even with advanced techniques to recover the data.
Basically trying to modify an existing file is a very advanced and rarely used technique. I have software that does that but the problems and pitfalls are many - don't do it!