Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading data from txt file in fortran

Tags:

format

fortran

I am writing a FORTRAN program that reads data from a text file and writing it to the console. the data file looks something like this

1234567890123456 123456.789 987654.321 673647.890 654356.890
6172876534567890 768909.098 234543.890 654321.908 987890.090

I have the following lines of FORTRAN code that reads data and just writes them to the console

 OPEN(1,FILE='data.txt')
    READ(1,'(I16,3F9.3)') A ,B, C, D
    WRITE (*, '(I16,3F9.3)') A,B,C,D
   CLOSE(1)

Instead of getting displayed as the same values in the text file, the following is the output

1234567890123456*********89987.656    0.322
6172876534567890*********98234.547    0.891

Can you please help me with this.

Thanks much

like image 310
Shenoy Tinny Avatar asked Jan 11 '12 23:01

Shenoy Tinny


1 Answers

Slight modification to the @Andrés Argüello Guillén answer.

Unlike most other solutions, my code does not force you to specify in advance the number of rows and columns.

CHARACTER(128) :: buffer

integer strlen, rows, cols
real, dimension(:,:), allocatable :: x

OPEN (1, file = 'matrix.txt', status='old', action='read')

!Count the number of columns

read(1,'(a)') buffer !read first line WITH SPACES INCLUDED
REWIND(1) !Get back to the file beginning

strlen = len(buffer) !Find the REAL length of a string read
do while (buffer(strlen:strlen) == ' ') 
  strlen = strlen - 1 
enddo

cols=0 !Count the number of spaces in the first line
do i=0,strlen
  if (buffer(i:i) == ' ') then
    cols=cols+1
  endif
enddo

cols = cols+1

!Count the number of rows

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

REWIND(1)

print*, 'Number of rows:', rows
print*, 'Number of columns:', cols

allocate(x(rows,cols))

do I=1,rows,1
  read(1,*) x(I,:)
  write(*,*) x(I,:)
enddo

CLOSE (1)

matrix.txt

0.0 1.0 2.0
3.0 4.0 5.0
6.0 7.0 8.0
like image 101
prograils Avatar answered Sep 19 '22 01:09

prograils