I am not a frequent user of the ENDFILE statement. Working with a code that uses it I am seeing
different behaviors from different compilers and am looking for clarification on what the standard
behavior is. Specifically the standard says …
Execution of an ENDFILE statement for a file connected for
sequential access writes an endfile record as the next record of
the file. The file is then positioned after the endfile record, which
becomes the last record of the file.
I am trying to interpret the intended meaning of “next record” as I
get different results truncating a sequential formatted file with
different compilers. Should the generated file from the following example have five or six lines in it?
$ ifort xx.f90 && ./a.out
rewind and read 5 lines
1 101
2 102
3 103
4 104
5 105
number of lines in file was 10 , is now 5
$ gfortran xx.f90 && ./a.out
rewind and read 5 lines
1 101
2 102
3 103
4 104
5 105
6 106
number of lines in file was 10 , is now 6
program demo_endfile
implicit none
integer :: lun, i, j, iostat
integer,parameter:: isz=10
!
! create a little scratch file
open(newunit=lun,file='_scr.txt', form='formatted')
write(lun,'(i0)')(100+i,i=1,isz)
!
! write end of file after reading half of file
rewind(lun)
write(*,*)'rewind and read',isz/2,'lines'
read(lun,*)(j,i=1,isz/2)
endfile lun ! will truncate line at current position
!
! NOTE: backspace before writing any addition lines
! once an ENDFILE(7f) statement is executed
! backspace(lun)
!
! rewind and echo remaining file
rewind(lun)
j=0
do i=1,huge(0)-1
read(lun,*,iostat=iostat)j
if(iostat.ne.0)exit
write(*,*)i,j
enddo
write(*,*)'number of lines in file was ',isz,', is now ',i-1
close(unit=lun,status='delete')
end program demo_endfile