Date Modified Category Fortran Tags Fortran

Fortran IO works with a simple logic. One needs to open the file before starting to read it. It can be done with open statement. unit, is the definition or ID of your file which that opened. Always call write and read with the ID of the you want to work on. Close your file at the end withe close.

Open files from Fortran, open

open (unit=15, file="data.dat", status='old',    &
             access='sequential', form='formatted', action='read' )
open (unit=9, file='array.dat', status='replace', action='write')

Write lines in a file or on screen, write

Unformatted write:

write(9,*)

Formatted write:

write(9,'(F4.3)')

Read lines from a file or screen, read

Unformatted read:

read(15,*)

Formatted read:

read(15,'(F4.3)')

Attention

Always read the file like you write it. It is as simple as only changing write staments to read.

Close files, close

Use the ID of the file you aim to close.

close(9)
close(15)

Fortran Formats

Formats can be used to write(read as well) in files or on screen.

For example:

fmt = "(I2,F3.5,E15.7)"
WRITE(*,fmt) 

Do you remember print*, x, it can be formatted as well,

print '(F7.3)', x

More explanation can be found at Shene's notes.

Example

Following example reads the data from a file with/without a format.

program readdata
  implicit none
  real, allocatable :: myData(:,:)
  real              :: myLine
  integer           :: i, j, myRow, myColumn
  character(len=30) :: myFileName
  character(len=30) :: myFormat

  myFileName='data.dat'

  open(99, file=myFileName)
  write(*,*)'open data file'
  read(99, *) myRow
  read(99, *) myColumn

  allocate(myData(myRow,myColumn))

  do i=1,myRow
    read(99,*) myData(i,:)
    !read(99,'(6(E11.4,X))') myData(i,:)
    print*, myData(i,:)
  enddo

  close(99)

end program readdata

To test, data given below is used.

2
6
2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35
2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35

If you are really interested to read your files with a format and if the number of columns are not constant you may need a format depending on a variable, please see related discussions here.