Degenerate Conic

Algorithms • Modern Fortran Programming • Orbital Mechanics

Mar 06, 2015

Fortran Stream I/O

Fortran 2003 introduced many new features to the language that make things a lot easier than they were in the bad old days. Deferred-length character strings and stream I/O are two examples. Deferred-length strings were a huge addition, since they allow the length of character variables to be resized on-the-fly, something never before possible in Fortran. (Note: if you happen to come across a Fortran 90 monstrosity called ISO_VARYING_STRING, avoid it like the plague. That is not what I'm talking about.) Stream I/O is also quite handy, allowing you to access files as a stream of bytes or characters. The following example uses both features to create a subroutine that reads in the contents of a text file into an allocatable string. Note that it uses the size argument of the intrinsic inquire function to get the file size before allocating the string.

subroutine read_file(filename,str)  
!  
! Reads the contents of the file into the allocatable string str.  
! If there are any problems, str will be returned unallocated.  
!  
implicit none

character(len=*),intent(in) :: filename  
character(len=:),allocatable,intent(out) :: str

integer :: iunit,istat,filesize

open(newunit=iunit,file=filename,status='OLD',&  
form='UNFORMATTED',access='STREAM',iostat=istat)

if (istat==0) then  
    inquire(file=filename, size=filesize)  
    if (filesize>0) then  
        allocate( character(len=filesize) :: str )  
        read(iunit,pos=1,iostat=istat) str  
        if (istat/=0) deallocate(str)  
        close(iunit, iostat=istat)  
    end if  
end if

end subroutine read_file  

References

  1. Stream Input/Output in Fortran [Fortran Wiki]
  2. Text file to allocatable string [Intel Fortran Forum] 03/03/2015