Fortran runtime error: End of file

浪尽此生 提交于 2019-12-08 07:09:05

问题


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.


回答1:


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.




回答2:


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

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