Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 469
Andrew Avatar asked Jun 24 '11 22:06

Andrew


People also ask

How do I read the last line of a file in Fortran?

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.

How does Fortran read files?

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.

What is read and write in Fortran?

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.


1 Answers

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.

like image 55
eriktous Avatar answered Sep 19 '22 14:09

eriktous