Fernando Brito Lopes
Fernando Brito Lopes

Reputation: 101

How can I read a 2D file which content is not separated by spaces in Fortran

I have a matrix stored in a file (number.txt), like this:

12323456  
54254311  
76534522  

How can I read such matrix in Fortran, so the result would be:

1 2 3 2 3 4 5 6  
5 4 2 5 4 3 1 1  
7 6 5 3 4 5 2 2  

It is very easy to separate these columns using awk and read it in Fortran. But, I would like to know if I can do all this using only Fortran. After I am done with I will need to multiple this matrix by its transpose.

Upvotes: 2

Views: 211

Answers (1)

francescalus
francescalus

Reputation: 32406

Fortran formatted input and output is based on fields. Fields are not required to be separated by spaces. Here you may consider the data 12323456 to be a single field of width 8 or 8 fields of width 1 (or other combinations).

If you want to read a value from a integer field of width 1, the format item I1 will allow that value to be read. If you have eight integer fields of width 1 next to each other 8I1 will allow reading of those.

implicit none
character(8) :: input(3)=['12323456','54254311','76534522']
integer i, values(8)

do i=1,3
  read(input(i),'(8I1)') values
  print '(8(I1,:,1X))', values
end do

end

Upvotes: 1

Related Questions