fortranでファイルを限界まで読み続けると、End of file でエラーが返って来る。この辺がなんとも原始的な香りを感じさせる。
この End of file を検出/処理するためには、以下の二通りが考えられる。
- END で行番号へ飛ぶ。
implicit none character( 99 ) :: input open( UNIT, FILE, STATUS = 'old' ) do while ( .true. ) read( UNIT, FORMAT, END = 999 ) input print *, input end do 999 print *, 'end of file'
End of file 時に、指定した行番号へ飛び、処理を続ける。
しかし、GoTo文がダサいという認識の下では、行番号に飛ぶのは度し難く感じる。
- IOSTAT で検出する。
【fortran】ファイル読み込みのコツ open, read | 理系夫婦の方程式
implicit none integer :: ios character( 99 ) :: input open( UNIT, FILE, STATUS = 'old' ) do while ( .true. ) read( UNIT, FORMAT, IOSTAT = ios ) input if ( ios == -1 ) then print *, 'end of file' exit end if print *, input end do
End of file 時に、IOSTATに -1 が代入され、処理が続けられる。こちらの方がスマートであろう。
ちなみに、End of file 時には変数(input)への代入は行われないため、最後の行の情報がそのまま変数inputの中に入っていることになる。