Fortran/Fortran simple input and output

From Wikibooks, open books for an open world
< Fortran
Jump to: navigation, search

← Fortran variables | Fortran Simple math →


A Fortran program reads from standard input or from a file using the read statement, and it can write to standard output using the print statement. With the write statement one can write to standard output or to a file. Before writing to a file, the file must be opened and assigned a unit number with which the programmer may reference the file. If one wishes to use the write statement to write a statement to the default output, the syntax is write(*,*). It is used as follows:

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

This code writes "Hello World!" to the default output (usually standard output, the screen), similar to if one had used the print* statement.

As a demonstration of file output, the following program reads two integers from the keyboard and writes them and their product to an output file:

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

The file "results.txt" will contain these lines:

 The product of 2 and 3
 is 6

Each print or write statement on a new line by default starts printing on a new line. For example:

program HelloWorld
  implicit none
 
  print*,"Hello"
  print*,"World!"
end program

Prints, to standard output:

Hello
World!

If one had put "Hello World!" in one print statement, the text "Hello World!" would have appeared on one line.