I am a Fortran novice. I would like to be able to read a text file and save its contents in individual variables. I found a very helpful Fortran tutorial (http://www.math.hawaii.edu/~hile/fortran/fort7.htm#read), and I am trying to follow one of the examples listed there. Specifically, I made a text file called data.txt with the following text:
1.23, 4.56, 7.89
11, 13, "Sally"
I have saved this text file in my current directory. Then, I have created a file test.f90 (also saving it in my current directory) containing the following code:
PROGRAM test
IMPLICIT NONE
REAL :: x, y, z
INTEGER :: m, n
CHARACTER first*20
OPEN(UNIT = 7, FILE = "data.txt")
READ(7,*) x, y, z
READ(7,*) m, n, first
PRINT *, x
PRINT *, y
PRINT *, z
PRINT *, m
PRINT *, n
PRINT *, first
END PROGRAM test
I am using the GNU Fortran compiler, which I think includes the features at least up to and including Fortran95. The above code appears to compile okay, at least with the default settings). But when I run the resulting executable, I get this error message:
At line 10 of file test.f90 (unit = 7, file = 'data.txt')
Fortran runtime error: End of file
Line 10 is the line READ(7,*) m, n, first. Can you please help me see what I am doing wrong in the above code?
It is not possible. Reading always starts from a certain point, and proceeds forward. By default it starts from the first byte; but you can jump to some other location. The critical issue is, in a free-format file, there is no way to know where the lines start unless you read the file.
In Fortran files are managed by unit identifiers. Interaction with the filesystem mainly happens through the open and inquire built-in procedures. Generally, the workflow is to open a file to a unit identifier, read and/or write to it and close it again.
This is sometimes called list directed read/write. read (*,*) list-of-variables write(*,*) list-of-variables. The first statement will read values from the standard input and assign the values to the variables in the variable list, while the second one writes to the standard output.
I can reproduce both your exact error message and the correct output. I'm using gfortran on Windows, and Notepad to create the data file.
If you terminate the second data line with an end-of-line character (by hitting the Enter key), the program will show the correct output; if you don't terminate it, it will display the error during execution.
Basically, the runtime tries to read a line, but encounters an end-of-file character before it reaches the end of the line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With