Modern Fortran Explained: Incorporating Fortran 2018 says on p278
A file already connected to one unit must not be specified for connection to another unit.
The Fortran 2018 standard merely says in section 12.5.4 that the results of doing so are compiler-dependent:
It is processor dependent whether a file can be connected to more than one unit at the same time.
If input/output operations are performed on more than one unit while they are connected to the same external the results are processor dependent.
Below is a code that simultaneously opens a file for reading and writing. The results by compiler are listed in the comments. Gfortran and ifort both allow a file to be read in one unit as it is written in another. Gfortran requires a FLUSH statement for this to work, but ifort does not. Flang and g95 give an error message when a file is connected to more than one unit. I think all of the compilers are standard-conforming.
program flush_file implicit none integer :: i,iter integer, parameter :: n = 10**3, inu = 10, outu = 11 character (len=*), parameter :: data_file = "random.txt" real, allocatable :: x(:),y(:) logical :: flushed allocate (x(n),y(n)) call random_number(x) print "(6a15)","flushed","minval(x)","maxval(x)","sum(abs(x-y))" do iter=1,2 flushed = iter == 1 open (unit=outu,file=data_file,action="write") open (unit=inu,file=data_file,action="read",status="old") do i=1,n ! write and read data from same file write (outu,*) x(i) if (flushed) flush(outu) read (inu,*) y(i) end do print "(l15,5f15.4)",flushed,minval(x),maxval(x),sum(abs(x-y)) close (outu) close (inu) end do end program flush_file ! sample ifort output: ! flushed minval(x) maxval(x) sum(abs(x-y)) ! T 0.0000 0.9957 0.0000 ! F 0.0000 0.9957 0.0000 ! sample gfortran output: ! flushed minval(x) maxval(x) sum(abs(x-y)) ! T 0.0005 0.9993 0.0000 ! At line 18 of file flush.f90 (unit = 10, file = 'random.txt') ! Fortran runtime error: End of file ! flang output: ! flushed minval(x) maxval(x) sum(abs(x-y)) ! FIO-F-207/OPEN/unit=10/file is already connected to another unit. ! File name = random.txt ! In source file flush.f90, at line number 14 ! g95 output: same as flang
Depending on the compilers that you use, maybe it’s ok to connect a file to different units for both input and output?