Fortran 文件结束错误



我正在学习Fortran,目前正在 fortrantutorials.com 上做练习。 我必须运行以下代码:

program magic    
implicit none
real, dimension(100) :: a,b,c,d
open(10, file='data.txt')
read(10,*) a
b = a*10
c = b-a
d = 1
print*, 'a = ', a
print*, 'b = ', b
print*, 'c = ', c
print*, 'd = ', d
end program magic

它读取以下数据.txt文件:

24
45
67
89
12
99
33
68
37
11

当我运行它时,它显示此错误:

At line 6 of file test.f95 (unit = 10, file = 'data.txt')
Fortran runtime error: End of file
[Finished in 0.0s with exit code 2]

第 6 行引用了以下行,我已经仔细检查了"data.txt"和我的 fortran 文件确实在同一个目录中:

read(10,*) a

我该怎么做才能解决此问题?提前谢谢。

read(10,*) a

尝试读取 100 个数字,因为a的大小为 100

real, dimension(100) :: a

您的文件不包含 100 个数字,因此当它到达文件末尾时会崩溃。

只需阅读编译器告诉您的消息:

"Fortran 运行时错误:文件结束">

如果你在读取中添加IOSTAT=<scalar-int-variable>,它将设置该变量而不是崩溃:

integer :: IOSTAT
CHARACTER*(128) :: IOMSG
open(10, file='data.txt')
read(10,*,IOSTAT=IOSTAT,IOMSG=IOMSG) a
IF ( IOSTAT .NE. 0 ) THEN
WRITE(*,*) "WARNING: Read failed with message '", TRIM(IOMSG), "'"
END IF

不要信任此类失败的 READ 语句的结果。

相关内容

最新更新