Skye Bleed
Skye Bleed

Reputation: 133

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.

Upvotes: 1

Views: 450

Answers (2)

owt
owt

Reputation: 11

If you need to read a file into a string, you should read the file in a loop until you reach its end and concatenate each string with the previous result. Something like this:

character (len = 256) :: string_all_file
character (len = 40) :: current_string

rows = 0 !Count the number of lines in a file
string_all_file = '';
DO
  READ(2, *, iostat=io) current_string
  IF (io/ = 0) EXIT
  rows = rows + 1
  string_all_file = string_all_file // current_string
END DO

I can make mistakes in the syntax. I haven't used fortran for a long time.

Upvotes: 1

steve
steve

Reputation: 900

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.

Upvotes: 3

Related Questions