Question

I need to open a file which I don't know if it exists each time I perform the open operation. If it exists I want to open it and store the information inside it into an array, do some calculations, clean the opened file and write the new information to it. If it doesn't exist I want to leave it open to write information to it.

I have to use fortran 77.

My code is:

 OPEN(7, FILE = "C:/Abaqus_JOBS/mELF.txt", 
1 action = "READ", status = "UNKNOWN")

My problem concerns status = "UNKNOWN", if the file exists I need to clean it (delete all data). How can do this?

Thanks

Was it helpful?

Solution

You can do this with the inquire statement:

logical :: file_exists
! ...

inquire(file='filename.txt',exist=file_exists)
if ( file_exists ) then
  ! Do stuff
else
  ! Do other stuff
endif

Or, since you are going to wipe the file anyway, just open it with status='replace' ;-) The difference between 'unknown' and 'replace' is, that 'replace' will create a new file will if it doesn't exist.

For FORTRAN 77, status='replace' does not exist. Then, the open statement could read:

open(1234, file='filename.txt', status='unknown', iostat=ierr)
if ( ierr .eq. 0) then
c    file opened successfully, delete 
  close(1234, status='delete')
endif

c Open a new file
open(1234, file='filename.txt', status='new', iostat=ierr)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top