File I/O

In many practical applications, program input and output are performed by read- ing from or writing to files. Before a file can be accessed from a Fortran program, it must be opened. The following example shows how a plain text file named out.txt may firstly be opened for writing and subsequently opened for reading:

program fileIO
implicit none
integer :: istat
real :: a,b
a=3.142

! Open a file called out.txt for writing. Its unit number is 101
open(101, file="out.txt", status="unknown", action="write", form="formatted", IOSTAT=istat)

! Check the file was opened successfully:
if (istat .NE. 0) then
write (*,*) "Error opening file"
exit
endif
write (101, '(f0.3)') a

! Once finished with the file it should be closed:
close(101)

! Open the file for reading - a different unit number (102) is used,
! but this is not necessary since we have closed the file
! associated with unit 101
open(102, file="out.txt", status="old", action="read", form="formatted", IOSTAT=istat)

! Check the file was opened successfully:
if (istat .NE. 0) then
write (*,*) "Error opening file"
exit
endif

! read the value from file and assign the value to b
! note that a total field width (5 in this case) must be
! supplied to the read function:
read (102, '(f5.3)') b
write (*,'(f5.3)') b
close(102)
end program fileIO

Program Output

3.142

Supported By

File Browser Reference
Department FHERIS
University of Galway
HEA Logo