Reading a comma delimited text file on a line in Fortran

I am a beginner Fortran. I would like to be able to read a text file and save its contents in separate variables. I found a very useful Fortran tutorial ( http://www.math.hawaii.edu/~hile/fortran/fort7.htm#read ) and I try to follow one of the examples there. In particular, I created a text file data.txt with the following text:

1.23, 4.56, 7.89 11, 13, "Sally" 

I saved this text file in my current directory. Then I created a test.f90 file (also saving it in the 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 use the GNU Fortran compiler, which I think includes features, at least until Fortran95 and including Fortran95. The above code seems to compile in order, 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, the first . Could you help me see what I am doing wrong in the above code?

+6
source share
3 answers

I can reproduce both your exact error message and the correct output. I use gfortran on Windows and Notepad to create a data file.
If you end the second line of data with the end of line character (by pressing the Enter key), the program will show the correct output; if you do not complete it, it will display a runtime error.

Basically, the runtime tries to read the line, but encounters the end-of-file character before it reaches the end of the line.

+2
source

When I use your trial program with your sample data, it worked! Congratulations! The output was:

  1.2300000 4.5599999 7.8899999 11 13 Sally 

To guess the possible reason why it does not work for you, sometimes Fortran executables may be sensitive to line endings, requiring the correct line terminator for the OS, including the last line of the data file. Conversely, many editors will silently convert line ends. I often encounter this problem with files written by Microsoft programs.

+3
source

For some compilers, it is important to add a new line after the last line of data. For example, gfortran is a compiler that needs this, and this is only logical. The Sun compiler (Oracle) does not need this.

+2
source

Source: https://habr.com/ru/post/891323/


All Articles