Thanks for all the replies.
The solution I prefer the most was sent to me by Phillip Helbig, and is
a variation on a suggestion by Nils Smeds. In my case it appears to be
the simplest to implement. The idea is to store the number of records at
the end of the file rather than the beginning, and to open the file for
reading with the position set to append (ie; positioned at the end of
the file before the end of file marker), to backspace by one to read the
number of records, and then rewind go back to the beginning of the file
and read all the records in.
An example program is appended.
This compiles and works fine with CVF and g95 on windows. However,
Phillip Helbig has gets a runtime error with this program using
DEC/Compaq/HP Fortran95 on VMS/Alpha, and both his compiler and PGI on
linux will only compile it if the file is opened for reading with
ACTION='READWRITE' rather than 'READ' even though there are no WRITE
statements.
Any ideas why?
Paul
PROGRAM test_rewind_prog
IMPLICIT NONE
INTEGER, PARAMETER :: unit=20
INTEGER :: record_1, record_2
INTEGER :: n_records
! Initialise
record_1=1
record_2=2
n_records=2
! Write to file
OPEN(&
& UNIT=unit,&
& FILE="test_rewind_prog.dat", &
& FORM='UNFORMATTED',&
& ACCESS='SEQUENTIAL',&
& ACTION='WRITE',&
& STATUS='REPLACE'&
& )
WRITE(UNIT=unit) record_1
WRITE(UNIT=unit) record_2
WRITE(UNIT=unit) n_records
CLOSE(UNIT=unit)
! Zero
record_1=0
record_2=0
n_records=0
! Read from file
OPEN(&
& UNIT=unit,&
& FILE="test_rewind_prog.dat", &
& FORM='UNFORMATTED',&
& ACCESS='SEQUENTIAL',&
& ACTION='READ',& !!
& STATUS='OLD',& !!
& POSITION='APPEND'& !!!
& )
BACKSPACE (UNIT=unit) !!!
READ(UNIT=unit) n_records
REWIND (UNIT=unit) !!!
READ(UNIT=unit) record_1
READ(UNIT=unit) record_2
CLOSE(UNIT=unit)
! Print to screen
PRINT *,n_records
PRINT *,record_1,record_2
END PROGRAM test_rewind_prog
|