037. Using read and write for file I/O#

topic: Input and Output

To read or write data from a file, it must first be connected to a unit. The newunit specifier, introduced in Fortran 2008, finds a free unit number.

The program below writes some data to a file and then reads it back. When the number of records1 in a file is unknown, set and check the iostat of read, as shown2.

write-read-file.f90 | | 0 | Godbolt Compiler Explorer logo | Fortran logo#
program read_write
   implicit none
   
   integer, parameter :: max_read = 10**6
   integer :: i, ierr, iunit, nread
   integer, allocatable :: vec_write(:), vec_read(:)
   character(len=*), parameter :: data_file = "temp.txt"
   
   vec_write = [1, 4, 9]

   ! Connect file to unit `iunit` for writing
   print *, "initial (unset) iunit =", iunit
   open (newunit=iunit, file=data_file, action="write", status="replace")
   print *, "iunit for writing =", iunit
   do i = 1, size(vec_write)
      write (iunit, *) vec_write(i)  ! Write one element of `vec_write` per line
   end do
   close (iunit)  ! Close the connection to the file

   ! Connect file to unit `iunit` for reading
   open (newunit=iunit, file=data_file, action="read", status="old")
   print *, "iunit for reading =", iunit
   allocate (vec_read(max_read))
   nread = max_read
   do i = 1, max_read
      read (iunit, *, iostat=ierr) vec_read(i)  ! Read one element of `vec_read` per line
      if (ierr /= 0) then  ! Reached end of file
         nread = i - 1
         exit
      end if
   end do
   print *, "# read =", nread
   print *, "data read =", vec_read(:nread)

end program read_write
Output3#
 initial (unset) iunit =           0
 iunit for writing =         -10
 iunit for reading =         -10
 # read =           3
 data read =           1           4           9

Note

The initial (unset) value of iunit here is compiler-dependent, and the used iunit values created by using newunit are compiler- and situation-dependent.



1

lines

2

and as in the previous tip

3

Compiled using GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0 with no flags