File Input/Output
Here we will generate some data and write it to a file:
! Program : Write output to a file
PROGRAM file_write
IMPLICIT NONE
INTEGER :: ii
OPEN(unit=10, file='output.dat', status='new')
DO ii = 1, 10
WRITE(1, '(i4)') ii*ii
ENDDO
CLOSE(unit=10)
END PROGRAM file_write
Note that unit=0
, 5
, and 6
are reserved. Do not use them to identify files
in your programs. Some older compilers might other other low unit numbers for
internal usage. It is safer and conventional to use unit number 10 and above for
user files.
Reading from file: we will read the data from file that is generated in the above example.
! Program : Read data from file
PROGRAM file_read
IMPLICIT NONE
INTEGER :: ii, data(10)
OPEN(unit=10, file='output.dat', status='old')
DO ii = 1, 10
READ(1, '(i4)') data(ii)
END DO
CLOSE(unit=10)
DO ii = 1, 10
PRINT '(i3)', data(ii)
END DO
END PROGRAM file_read
FORTRAN Namelist
FORTRAN Namelist provides an easy way to read and write groups of variables. Namelists simplify reading and writing variables to files without needing to specify variable formats for each I/O operation. The namelist group is defined in the Fortran code, and the corresponding input/output text uses a specific format:
- Begins with
&groupname
- Lists variable assignments (comma or space separated)
- Ends with
/
.
Namelist example
Namelists are used in Quantum ESPRESSO input files.
Here is an example namelist:
&SYSTEM
ibrav = 2
nat = 2
ntyp = 1
ecutwfc = 30.0
ecutrho = 240.0
/
We can read and parse various inputs following way:
program read_qe_input
implicit none
! Declare variables matching those in the QE SYSTEM namelist
integer :: ibrav, nat, ntyp
double precision :: ecutwfc, ecutrho
character(len=256) :: input_file
integer :: ios
! Namelist definition
namelist /SYSTEM/ ibrav, nat, ntyp, ecutwfc, ecutrho
! Set default values
ibrav = 0
nat = 0
ntyp = 0
ecutwfc = 0.0d0
ecutrho = 0.0d0
! Set input file name
input_file = '30_qe.in'
! Open and read the SYSTEM namelist
open(unit=10, file=input_file, status='old', action='read')
read(10, nml=SYSTEM, iostat=ios)
if (ios /= 0) then
print *, "Error reading SYSTEM namelist from file ", trim(input_file)
else
print *, "ibrav =", ibrav
print *, "nat =", nat
print *, "ntyp =", ntyp
print *, "ecutwfc =", ecutwfc
print *, "ecutrho =", ecutrho
end if
close(10)
end program read_qe_input