I'm trying to understand how the READ statement works in Fortran. To do this, I've written the following simple program:
program main
integer a,b,c
open(unit=10,file='test.txt',status='old')
read(10,*)a,b,c
print*,a,b,c
close(10)
end program main
I run this on the terminal (using a Mac): gfortran Main.f95; open a.out
I get the following error: At line 5 of file Main.f95 (unit = 10, file = 'test.txt') Fortran runtime error: End of file
I've looked for solutions all around the web and came upon the suggestion of adding IOSTAT=... inside the READ specifiers, as follows:
program main
integer a,b,c,IOstatus
open(unit=10,file='test.txt',status='old')
read(10,*,IOstat=IOstatus)a,b,c
print*,a,b,c,IOstatus
close(10)
end program main
When I do this, the program runs successfully. However, the print command displays "2 0 1 -1", which is erroneous as the test.txt file contains "1,2,3".
I've tried tweaking things here and there, but no good. I'm trying to do something that (I think) should be very simple: reading a list of integers from a .txt file. Any help as to what I'm doing wrong would be GREATLY appreciated.
I think that your problem is related with the text.txt
file rather than the Fortran code. Try to add and end-of-line character (enter) in it. I have successfully run your original code with gfortran 5.4.
See this related post for more details.
Your program is doing the right thing. Simply testing for iostat prevents teh program from crashing. IOstatus is set to a negative number (in this case -1) if the end of file was reached. IOstatus is set to a positive number if there was a read error, which did not happen in your case. Therefore, your print statement ends with -1, which is correct.
来源:https://stackoverflow.com/questions/46248138/fortran-runtime-error-end-of-file