NAMELIST IOを利用したパラメータ入力の例文

諸般の事情により、共同研究者がFortranで開発してくれた計算プログラムを用いて研究をしています。計算パラメータがソースファイルに直書きだったので、Fortranの入出力をいろいろ調べていました。どうやら、Fortran2003でようやく標準化された入出力が準備されたようで、試したところ、少なくともgfortran 4.4とIntel Fortran Compiler for Linux 11.0では、namelistの内部read文以外は動くようでした。サンプルプログラムはそれなりに見つかったのですが、iostatusまでまじめに考慮したサンプルが見つからなかったので、とりあえず書いてみました。エラーが負だったり正だったりと、過去の遺産からかばらばらなのが、面倒です。
このサンプルでは、コマンドラインに複数のパラメータファイルを指定して、それぞれ読み込んで、値を出力するようにしています。

program main
  implicit none

  integer :: a,b,c

  integer :: clcount
  character(len=256) :: arg
  integer :: arglen,argerr
  integer :: ioerr
  integer :: i

  namelist /param/ a,b,c
  a=1
  b=2
  c=2

  clcount=command_argument_count()
  if (clcount == 0) then
    stop "*** no input file specified ***"
  endif
  do i=1,clcount
    call get_command_argument(i,arg,arglen,ioerr)
    if (ioerr > 0) then
      stop "*** input file name retrieval fails ***"
    elseif (ioerr == -1) then
      stop "*** input file name too long ***"
    endif
    open(unit=100,file=arg,iostat=ioerr)
    if (ioerr > 0) then
      stop "*** Cannot open input file ***"
    endif
    read(unit=100,nml=param,iostat=ioerr)
    if (ioerr < 0) then
      print*,"*** parameter reading FAILED. Use default value instead ***"
    endif
    close(unit=100)
    write(unit=6,nml=param)
  enddo
end program main