简体   繁体   中英

Reading a comma-delimited text file line-by-line in Fortran

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?

When I your sample program, with your sample data, it worked! Congratulations! Output was:

   1.2300000    
   4.5599999    
   7.8899999    
          11
          13
 Sally 

To guess a possible reason that it isn't working for you, sometimes Fortran executables can be sensitive to line endings, demanding the correct line-terminator for the OS, including on the last line of a data file. Conversely many editors will silently convert line endings. I commonly run into this problem with files written by Microsoft programs.

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.

For some compilers it is important to add a new line after the last line with the data. For example gfortran is a compiler which needs that and it is quite logical. The Sun (Oracle) compiler doesn't need that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM