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.
An IOSTAT value is a value assigned to the variable for the IOSTAT= specifier if an end-of-file condition, end-of-record condition or an error condition occurs during an input/output statement. There are five types of error conditions: catastrophic, severe, recoverable, conversion, Fortran 90 and Fortran 95 language.
The CLOSE statement disconnects a file from a unit. Unit identifier for an external unit. If UNIT= is not used, then u must be first. Determines the disposition of the file-- sta is a character expression whose value, when trailing blanks are removed, can be KEEP or DELETE .
The ERR =s clause is optional. s is a statement label of a statement to branch to if an error occurs during execution of the OPEN statement.
Reading from and Writing into the FileThe END = s specifier is a statement label where the program jumps, when it reaches end-of-file. This example demonstrates reading from and writing into a file. In this program we read from the file, we created in the last example, data1.
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:
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
inquire
statement to figure out whether the file exists where your program is looking for it.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With