Fortran/テキスト入出力

出典: フリー教科書『ウィキブックス(Wikibooks)』

Fortranプログラムは、read文を使用して標準入力またはファイルから読み取り、print文を使用して標準出力に書き込むことができます。write文を使用すると、標準出力またはファイルに書き込むことができます。ファイルに書き込む前に、ファイルをオープンし、プログラマがファイルを参照するためのユニット番号を割り当てる必要があります。write文を使用してデフォルトの出力にステートメントを書き込む場合、構文はwrite(*,*)となります。使い方は以下の通りです。

program hello_world
    implicit none
    write (*,*) "Hello World!"
end program

このコードは、"Hello World!"をデフォルトの出力(通常は標準出力、画面)に書き込みます。これはprint *,ステートメントを使用した場合と同様です。

ファイル出力[編集]

ファイル出力のデモとして、次のプログラムはキーボードから2つの整数を読み取り、その整数と積を出力ファイルに書き込みます。

program xproduct
    implicit none
    integer :: i, j
    integer, parameter :: out_unit=20

    print *, "enter two integers"
    read (*,*) i,j

    open (unit=out_unit,file="results.txt",action="write",status="replace")
    write (out_unit,*) "The product of", i, " and", j
    write (out_unit,*) "is", i*j
    close (out_unit)
end program xproduct

ファイル "results.txt" にはこれらの行が含まれます。

results.txt
The product of 2 and 3
is 6

デフォルトでは、各printまたはwriteステートメントは新しい行に印刷を開始します。例えば、以下のようになります。

program hello_world
    implicit none

    print *, "Hello"
    print *, "World!"
end program

標準出力に出力します。

Hello
World!

もし、"Hello World!"を1つのprint文に入れていたら、"Hello World!"というテキストが1行に表示されたことになります。