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

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

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

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

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

            if (rc /= 0) &
                exit

            print '(i1, a, a)', i, ': ', trim(buffer)
        end do
    else
        stop 'Reading file "', fname, '" failed: ', 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 has to 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(record), dimension(6) :: missions

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().