Files

In order to read from or write to files, one has to open a file with the open statement at first. Finally, a file is closed with the close statement.

open ([unit=] u, list)
Specifier Values Default Function
access direct, sequential, stream sequential access mode (optional)
action read, readwrite, write readwrite file access (optional)
asynchronous no, yes no asynchronous I/O (optional)
blank null, zero null interpretation of blanks (optional)
decimal comma, point point decimal edit mode (optional)
delim apostrophe, none, quote none delimiter for character constants (optional)
encoding default, utf-8 default encoding form for file (optional)
err label error transfer control (optional)
file character file name or * (optional)
form formatted, unformatted depends on access format type (optional)
iostat integer I/O status (optional)
newunit integer returns unused unit number (optional)
pad no, yes yes record padding (optional)
position append, asis, rewind asis file positioning (optional)
recl integer record length (optional)
status old, new, scratch, replace, unknown unknown file status at open (optional)
unit integer unit number (mandatory)

Reading Files

A text file data.txt 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:

! reader.f90
program main
    use, intrinsic :: iso_fortran_env
    implicit none

    character(len=*), parameter :: F = 'data.txt'   ! File name.
    integer,          parameter :: U = 20           ! Output unit.
    character(len=100)          :: street
    integer                     :: i, rc

    open (unit=U, action='read', file=F, iostat=rc)

    if (rc == 0) then
        do
            read (U, *, iostat=rc) i, street            ! Read from file.
            if (rc /= 0) exit                           ! Exit on error.
            print '(i1, a, a)', i, ': ', trim(street)   ! Output line.
        end do
    else
        write (error_unit, '(3a, i0)') 'Reading file "', F, '" failed: error ', rc
        stop
    end if

    close (U)
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)

Open the CSV file and iterate over the file contents to read all lines into the array:

do i = 1, 6
    read (U, *) 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, re-allocate the array on each iteration using the intrinsic Fortran routine move_alloc() or use a linked list instead.

Writing Files

Writing to files does not differ much from reading from files. A file has to be opened for writing, using either action='write' or action='readwrite' in the open statement. One can then append data with the write statement and the output unit of the opened file. The example below writes the string Hello, World! to file hello.txt.

! writer.f90
program main
    use, intrinsic :: iso_fortran_env
    implicit none

    character(len=*), parameter :: F = 'hello.txt'  ! File name.
    integer,          parameter :: U = 20           ! Output unit.
    integer                     :: rc

    open (unit=U, action='write', file=F, status='replace', iostat=rc)

    if (rc == 0) then
        write (U, '(a)') 'Hello, World!'
    else
        write (error_unit, '(3a, i0)') 'Writing to file "', F, '" failed: error ', rc
        stop
    end if

    close (U)
end program main