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, intrinsic :: iso_fortran_env
    implicit none

    character(len=*), parameter :: fn = 'data.dat'  ! File name.
    integer,          parameter :: fh = 10          ! File handle.

    character(len=100) :: buffer
    integer            :: rc, i

    open (unit=fh, file=fn, action='read', iostat=rc)

    if (rc == 0) then
            read (fh, *, iostat=rc) i, buffer

            if (rc /= 0) &

            print '(i1, a, a)', i, ': ', trim(buffer)
        end do
        print '(3a, i0)', 'Reading file "', fn, '" failed: error ', rc
    end if

    close (fh)
end program main

Reading CSV files

In order to read files containing comma-separated values (CSV), a type representing the data structure can be declared. Assume a CSV file with the following contents:

Vostok 1,1961,Yuri Gagarin
Vostok 2,1961,Gherman Titov
Vostok 3,1962,Andriyan Nikolayev
Vostok 4,1962,Pavel Popovich
Vostok 5,1963,Valery Bykovsky
Vostok 6,1963,Valentina Tereshkova

A proper type declaration for this data set may be:

type :: mission
    character(len=8)  :: name
    integer           :: year
    character(len=20) :: pilot
end type mission

type(mission) :: missions(6)

Then, open the CSV file and iterate over the file contents to read all lines into the array:

do i = 1, 6
    read (fh, *) missions(i)
end do

The result is an array of mission types that can be easily accessed:

print *, missions(1)%pilot

The number of lines in the files has to be known in advance. Otherwise, it is necessary to re-allocate the array on each iteration using the intrinsic Fortran routine move_alloc().