Write in an existing file without overwriting in Fortran

maxhaz picture maxhaz · Oct 25, 2013 · Viewed 13k times · Source

I have an existing file written by a Fortran program (formatted) and I would like to add few lines at the beginning of the file. The idea is to do so without making a copy of the original file.

I could add a line at the end of the file with:

open(21,file=myfile.dat,status='old',action='write',
        form='formatted',position="append")
write(21,*) "a new line"

but when I tried:

open(21,file=myfile.dat,status='old',action='write',
        form='formatted',position="rewind")
write(21,*) "a new line"

it overwrites the whole file.

It might be impossible. At least, I would be glad to have a confirmation that it is effectively impossible.

Answer

Vladimir F picture Vladimir F · Oct 25, 2013

Yes, it is impossible. With position= you only set the position for writing. Normally you just delete everything past the current record by a write in a sequential file. You may be able to adjust a record at the beginning in a direct access file, but also not just add something at the beginning. You have to make a copy first.