可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.