Getting fortran runtime error: end of file

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I have recently learned how to work with basic files in Fortran and I assumed it was as simple as:

open(unit=10,file="data.dat") read(10,*) some_variable, somevar2 close(10)  

So I can't understand why this function I wrote is not working. It compiles fine but when I run it it prints:

fortran runtime error:end of file 

Code:

Function Load_Names()  character(len=30) :: Staff_Name(65) integer :: i = 1  open(unit=10, file="Staff_Names.txt")  do while(i < 65)  read(10,*) Staff_Name(i) print*, Staff_Name(i) i = i + 1  end do  close(10) end Function Load_Names 

I am using Fortran 2008 with gfortran.

回答1:

A common reason for the error you report is that the program doesn't find the file it is trying to open. Sometimes your assumptions about the directory in which the program looks for files at run-time will be wrong.

Try:

  • using the err= option in the open statement to write code to deal gracefully with a missing file; without this the program crashes, as you have observed;

or

  • using the inquire statement to figure out whether the file exists where your program is looking for it.


回答2:

You can check when a file has ended. It is done with the option IOSTAT for read statement. Try:

Function Load_Names()  character(len=30) :: Staff_Name(65) integer :: i = 1 integer :: iostat  open(unit=10, file="Staff_Names.txt")  do while(i < 65)   read(10,*, IOSTAT=iostat) Staff_Name(i)   if( iostat < 0 )then    write(6,'(A)') 'Warning: File containts less than 65 entries'    exit   else if( iostat > 0 )then    write(6,'(A)') 'Error: error reading file'    stop   end if   print*, Staff_Name(i)   i = i + 1 end do  close(10) end Function Load_Names 


回答3:

Using Fortran 2003 standard, one can do the following to check if the end of file is reached:

    use :: iso_fortran_env      character(len=1024) :: line     integer :: u1,stat      open (newunit=u1,action='read',file='input.dat',status='old')  ef: do       read(u1,'A',iostat=stat) line       if (stat == iostat_end) exit ef ! end of file       ...     end do ef     close(u1) 


回答4:

Thanks for all your help i did fix the code:

Function Load_Names(Staff_Name(65))!Loads Staff Names      character(len=30) :: Staff_Name(65)     integer :: i = 1      open(unit=10, file="Staff_Names.txt", status='old', action='read')!opens file for reading      do while(i < 66)!Sets Set_Name() equal to the file one string at a time          read(10,*,end=100) Staff_Name(i)         i = i + 1      end do      100 close(10)!closes file     return!returns Value end Function Load_Names 

I needed to change read(10,*) to read(10,*,END=100) so it knew what to do when it came to the end the file as it was in a loop I assume.



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