2017-06-13 125 views
0

我正在学习Fortran,目前正在fortrantutorials.com上进行练习。我必须运行下面的代码:Fortran文件错误结束

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 

它读取以下的data.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 

我能做些什么来解决这个问题?提前致谢。

+0

data.txt是否有(至少)100行? – francescalus

回答

1
read(10,*) a 

尝试读取100个数字,因为a尺寸为100

real, dimension(100) :: a 

您的文件不包含100个号码,所以当它到达文件的末尾崩溃。

只需读取消息编译器会告诉你:

"Fortran runtime error: End of file"

1

如果添加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语句。