はじめに
第6回はファイル操作です。
ファイル操作は言語によって結構書き方が異なったり、いろんなパラメータを設定できたりします。
ファイル操作の方法
ファイル操作は、open, read, write, closeを用いて行います。
具体例
program fileHandling implicit none integer :: unit_number = 10 real :: temperature ! Open the file for reading open(unit=unit_number, file='temperatures.dat', status='old', action='read') ! Read the first temperature read(unit=unit_number, fmt=*) temperature print *, 'First temperature: ', temperature ! Close the file close(unit=unit_number) ! Open the file again for appending open(unit=unit_number, file='temperatures.dat', status='unknown', action='write', position='append') ! Write a new temperature to the file write(unit=unit_number, fmt=*) 'New temperature: 20.5' ! Close the file close(unit=unit_number) end program fileHandling
unit: 開いたデータに対する固有の値。
file: ファイル名
status: oldは既存ファイル。unknownはファイルがなければwriteした内容でをファイルを作成。
position: 次の操作を行うポインタの位置、appendなら既存データの末尾の後ろ。
readの後の変数は、読み込んだ内容を代入する変数。
writeの後の内容は、ファイルに書き込む内容。
まとめ
今回はファイル操作について解説しました。コンソールからファイルに入力する操作は、普段あまり使わないし、今ファイルがどうなっているか書き込み中にリアルタイムでわからないので少し難しいですね。
第7回は外部ルーチン・外部関数です。
注意
このページは大学のFortranの授業の予習で書いています。
直観的な理解をメモしているだけなので、厳密なところでは誤りがあるかもしれません。