Namelists

Namelists are an I/O feature for format-free input and output of variables by key-value assignments that were first introduced by some FORTRAN 77 compilers, but then became a Fortran 90 standard later. Most compilers offer extensions to the Namelist standard. Fortran variables can be read from and written to plain-text files in a standardised Namelist format, usually with file-ending .nml.

The namelist statement is used to define the identifier and the variables that a part of the Namelist.

integer            :: i
integer            :: j
character(len=128) :: str

namelist /EXAMPLE/ i, j, str

Variable names inside a Namelist are case-insensitive.

! example.nml
&example
i=5,
j=17,
str='Hello, World!'
/

In order to read a Namelist from stdin or file, we just pass our Namelist via the nml attribute in the read statement:

read (nml=EXAMPLE, unit=fu)

We can write Namelists to stdout or file in the very same way by setting the nml attribute in the write statement:

write (nml=EXAMPLE, unit=fu)

Reading Namelist Files

The Namelist EXAMPLE in file example.nml:

&EXAMPLE
x=100
y=500
r(1)=10.5
r(2)=20.25
alice%id=1
alice%name='Alice'
alice%age=27
/

Fortran source file example.f90:

! example.f90
program main
    implicit none

    type :: person_type
        integer           :: id
        character(len=32) :: name
        integer           :: age
    end type person_type

    character(len=*), parameter :: INPUT_FILE = 'example.nml'
    integer                     :: x, y
    real                        :: r(2)
    type(person_type)           :: alice

    ! Namelist definition.
    namelist /EXAMPLE/ x, y, r, alice

    ! Set initial values.
    alice = person_type(1, 'Jane Doe', 0)
    x = 0; y = 0
    r = [ 0.0, 0.0 ]

    ! Read Namelist file.
    call read_namelist(INPUT_FILE)

    ! Output some values.
    print '(a, i0)', 'PERSON ID:   ', alice%id
    print '(2a)',    'PERSON NAME: ', alice%name
    print '(a, i0)', 'PERSON AGE:  ', alice%age
contains
    subroutine read_namelist(file_path)
        !! Reads Namelist from given file.
        character(len=*), intent(in) :: file_path
        integer                      :: fu, rc

        ! Check, if file exists.
        inquire (file=file_path, iostat=rc)

        if (rc /= 0) then
            print '(3a)', 'Input file "', trim(file_path), '" does not exist.'
            return
        end if

        ! Open and read Namelist file.
        open (action='read', file=file_path, iostat=rc, newunit=fu)
        read (nml=EXAMPLE, iostat=rc, unit=fu)

        if (rc /= 0) then
            print '(a)', 'Invalid Namelist format.'
        end if

        close (fu)
    end subroutine read_namelist
end program main

The example program prints the values read from the Namelist file. The default values are shown if the import fails:

$ gfortran10 -o example example.f90
$ ./example
PERSON ID:   1
PERSON NAME: Alice
PERSON AGE:  27