Files

Reading Files

A text file data.dat with an arbitrary number of lines is given:

1, "Mediterranean Avenue"
2, "Baltic Avenue"
3, "Oriental Avenue"
4, "Vermont Avenue"
5, "Connecticut Avenue"
6, "St. Charles Place"

The following example can be used to read and output the file contents:

! file.f90
program main
    use iso_fortran_env
    implicit none

    character(len=*), parameter :: fname = 'data.dat'
    integer,          parameter :: fh = 10

    character(len=100) :: buffer
    integer            :: io
    integer            :: i

    open(unit=fh, file=fname, action='read', iostat=io)

    if (io == 0) then
        do
            read (fh, *, iostat=io) i, buffer
            if (io /= 0) exit

            write (*, '(i1 a a)') i, ': ', trim(buffer)
        end do
    else
        write (*, *) 'Reading file "', fname, '" failed: ', io
    end if

    close(fh)
end program main