Search code examples
fileiofortran

read file character by character fortran


I'm using GNU fortran. I'd like to be able to read a file into a string, and then iterate over every character in that file OR simply read the file character by character. Here's what I tried:

character(len=:) , allocatable :: content
! this would normally allocate to the file size, but I'm making a minimal example
allocate(character(256) :: content) 
open(unit=2, file='test.txt', status='old')
read(2, *) content
close(2)
print *, content

But this only prints the first line and I'm not really sure why.


Solution

  • If you name this code 'a.f90' and compile it will print itself.

    program foo
       character(len=:), allocatable :: str
       integer fd
       allocate(character(len=216) :: str)
       open(newunit=fd, file='a.f90', access='stream')
       read(fd) str
       close(fd)
       print *, str
    end program foo
    

    BTW, to make this more useful, you can use inquire(file='a.f90', size=sz) to determine the file size, and then do the allocation with allocate(character(len=sz-1) :: str). The minus 1 removes EOF.