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

怎甘沉沦 提交于 2020-01-01 09:55:07

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6474410/reading-a-comma-delimited-text-file-line-by-line-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!