HP Fortran Programmer's Reference (September 2007)

I/O and file handling
Example programs
Chapter 8232
IOSTAT=ios1, ERR=99, RECL=16)
! Use nonadvancing I/O to suppress newline at the end of output
! record, thus keeping the prompt on the same line with the
! input.
WRITE (6, FMT='(A)', ADVANCE='NO') &
' Enter number to insert in list: '
READ *, number_to_insert
! Read from sorted list and write to scratch file until we find
! where to insert number; then, write number_to_insert, and
! continue writing remaining sorted numbers to scratch file.
DO WHILE (ios1 >= 0) ! loop only if OPEN didn’t encounter EOF
! The END=15 specifier in the READ statement gets us out of
! the loop, once we’re in it.
READ (18, *, END=10, IOSTAT=ios2, ERR=99) number_in_list
IF (number_to_insert <= number_in_list) THEN
rec_num = rec_num + 1 ! add the new record
WRITE(17, 100, REC=rec_num) number_to_insert
DO
rec_num = rec_num + 1
WRITE(17, 100, REC=rec_num) number_in_list
READ (18, *, END=15, IOSTAT=ios2, ERR=99) number_in_list
END DO
ELSE
rec_num = rec_num + 1
WRITE (17, 100, REC=rec_num) number_in_list
END IF
END DO
! The file is empty or the item goes at the end of file. Add 1
! to rec_num for the record to be inserted.
10 rec_num = rec_num + 1
WRITE (17, 100, REC=rec_num) number_to_insert
! Copy the scratch file to the data file. But first rewind
! so that we start writing at beginning of the data file.
15 REWIND 18
! Read from scratch file and write to data file
DO i = 1, rec_num
READ (17, 100, REC=i) number_in_list
WRITE (18, *) number_in_list
END DO
CLOSE (18)
CLOSE (17)
STOP 'Inserted!'
! Error handling section
99 IF (ios1 /= 0) THEN
WRITE (7, 200) ”Open error = ”, ios1
ELSE
WRITE (7, 200) ”Read error = ”, ios2