Skip to content
Fortran

File I/O and Formatting

Read/write files with formatted output.

By EZ4Code Team
iofileformat

Code

! Write to file
open(unit=10, file='output.txt', status='replace')
write(10, '(A, I0, A)') 'Count = ', 42, ' items'
write(10, '(F8.2)') 3.14159   ! '    3.14'
close(10)

! Read from file
open(unit=11, file='input.txt', status='old')
do
  read(11, '(A)', iostat=ios) line
  if (ios /= 0) exit
  print *, trim(line)
end do
close(11)

! Namelist (config files)
namelist /config/ nx, ny, dt, max_iter
nx = 100; ny = 100; dt = 0.01; max_iter = 1000
open(unit=12, file='config.nml')
write(12, nml=config)
close(12)

! Internal I/O (string <-> number)
character(20) :: str
real :: x
write(str, '(F0.4)') 3.14159  ! str = '3.1416'
read(str, *) x                ! x = 3.1416

Explanation

Fortran uses unit numbers (integers) for file handles. Format strings like '(F8.2)' control output width/precision. iostat returns non-zero on EOF or error — use to detect end of file. Namelist is a config-file format built into Fortran. Internal I/O converts between strings and numbers (like sprintf/sscanf).

More Fortran Snippets