Chelo Barros
Chelo Barros

Reputation: 21

Unable to read a number from a text file

I am using Fortran to make a subroutine to use in a CFD shallow water software.

I have written this code to read and use the values stored.

PROGRAM hieto

! Calcula la precipitacion efectiva en funcion del tiempo
!IMPLICIT NONE

real::a

!Abrir CSV
!OPEN(UNIT=10,FILE="datos.txt",FORM="formatted",STATUS="replace",ACTION="readwrite",ACCESS='sequential')
open(unit=10, file='datos.txt')

!Leer el archivo
read(10, *, iostat=ios)a
print*,ios
print*, a
close (UNIT=10)

END PROGRAM hieto

My text file datos, looks like this

1

2

3

When I run the code as is, I get the following output

-1 
0.0000000000
Process return 0 (0x0) execution time: 0.002 s

the first number in the row one is one not zero, so I don't know why this happens.

And if I remove the iostat=ios from the read statement, I get the following error:

At ine 13 (the line od the read stament) of file /home/Dropbox/scripts_tesis/fortran/hieto_telemac.f90 (unit=10, file=datos.txt')
Fortran runtime error: end of file.
Proceess returned 2 (0x2)

I have read some answers here so I tried adding end=3 in the read statement, and also to end my text file with a blank line at the end. The end=3 gives an error saying 3 is not a defined label and putting a blank row in the text file does nothing.

I am using ubuntu 16.04 LTS and Gfortran compiler.

Upvotes: 1

Views: 155

Answers (1)

What happens is that your file is empty.

Make sure that there is indeed a file called datos.txt in that directory. Pay attention to the exact name. datos.txt and just datos is not the same thing.

If you tried to open it before with the commented command that includes STATUS="replace" your old file would have been replaced.

And because the file is empty, you didn't real anything useful. If iostat is non-zero, and your is -1, then the value of the variable being read is undefined. So your a is undefined. Again, because your file is empty.

Additionally, you cannot just blindly put end=3 in your code because you saw it somewhere on Stack Overflow. You must first understand what it is supposed to do. There is no reason to combine iostat= and end=. The iostat is perfectly sufficient.

Upvotes: 4

Related Questions