in reply to read from a file and write into the same file
I'd suggest you just write to another file and then copy the result over the original.