PROGRAM Direct_Access_File_Demo
!-----------------------------------------------------------------------
!  Program to read a part number during execution, access a record in
!  a direct-access parts inventory file, and display this record.
!  Variables used are:
!    RecordLength : length of records in the file (parameter)
!    PartNumber   : a part number, 0 if invalid part number;
!                   otherwise nonzero
!    BadNumber    : indicates if record number was bad
!    FileName     : name of the file
!    PartsRecord  : a record in the file
!
!  Input (keyboard): FileName, PartNumber
!  Input (file):     PartsRecord
!
!  Output (screen):  User prompts, PartsRecord, or error message and
!                    PartNumber for an invalid part number
!-----------------------------------------------------------------------

   IMPLICIT NONE

   INTEGER, PARAMETER :: RecordLength = 30
   INTEGER :: PartNumber, BadNumber

   CHARACTER*20 :: FileName, PartsRecord*(RecordLength)

! Get the name of the file and open it for direct access

   PRINT *, "Enter name of file: "
   READ "(A)", FileName
   OPEN (UNIT = 10, FILE = FileName, STATUS = "OLD", &
         ACCESS = "DIRECT", FORM = "FORMATTED",  &
         RECL = RecordLength)

! Repeat the following so long as there are more
! part numbers to process:

   DO
      PRINT *
      PRINT *, "Enter part number (0 to stop): "
      READ *, PartNumber

      IF (PartNumber == 0) EXIT

      READ (10, "(A)", REC = PartNumber, IOSTAT = BadNumber) PartsRecord
      IF (BadNumber == 0) THEN
         PRINT '(1X, "Part", I3, ": ", A)', PartNumber, PartsRecord
      ELSE
         PRINT '(1X, "Invalid part number: ", I3)', PartNumber
      END IF
   END DO

   CLOSE(10)

END PROGRAM Direct_Access_File_Demo
