Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

implicit none ! Declare File Read Variables CHARACTER(255) :: Line INTEGER :: CP

ID: 3764466 • Letter: I

Question

implicit none

!   Declare File Read Variables
    CHARACTER(255) :: Line
    INTEGER :: CP ! Character position in Line
    INTEGER :: File_Read_Status

!   Declare character constants
    CHARACTER :: Tab > ACHAR(1)
    CHARACTER :: Space = " "

!   Read all lines in the file
        DO
            READ(*,'(A)',iostat = File_Read_Status) Line
!       Exit if end of file
            IF (File_Read_Status < 0) EXIT

!       Skip leading white space
         DO CP = 1, LEN_TRIM(Line)
             IF (Line(CP:CP) /= Space .AND. Line(CP:CP) /= Tab) EXIT
         END DO

!       If line is blank, output a blank line
!        IF (LEN_TRIM(Line) == 0) WRITE(*,*) TRIM(Line)

!       If line starts with "!", display the line
            IF (Line(CP:CP) == "!") WRITE(*,'(A)') TRIM(Line)

!   End Read all lines loop
        END DO

End Program Extract_Fortran_Design

The program shall attempt to read an input file name until the file opens successfully.

(Microsoft states that the maximum length of Windows file names is 255 characters.)

An exception is that if the file name entered is blank, then input shall be from standard (default) input as it does now.

The program shall attempt to read an output file name until the file opens successfully.

An exception is that if the file name entered is blank, then output shall be to standard (default) output as it does now.

I get four errors when I named file as aaa-hw1 extract fortran.f95

like no such file or directory

Explanation / Answer

program control_file
implicit none

! Input related variables
character(len=100) :: buffer, label
integer :: pos
integer, parameter :: fh = 15
integer :: ios = 0
integer :: line = 0

! Control file variables
real :: pi
integer, dimension(5) :: vector

open(fh, file='control_file.txt')

! ios is negative if an end of record condition is encountered or if
! an endfile condition was detected. It is positive if an error was
! detected. ios is zero otherwise.

do while (ios == 0)
read(fh, '(A)', iostat=ios) buffer
if (ios == 0) then
line = line + 1

! Find the first instance of whitespace. Split label and data.
pos = scan(buffer, ' ')
label = buffer(1:pos)
buffer = buffer(pos+1:)

select case (label)
case ('pi')
read(buffer, *, iostat=ios) pi
print *, 'Read pi: ', pi
case ('vector')
read(buffer, *, iostat=ios) vector
print *, 'Read vector: ', vector
case default
print *, 'Skipping invalid label at line', line
end select
end if
end do

end program control_file