这个fortran问题是怎么设计的

img

这应该是fortran一行一行读入文件时的时候,错误数值比如说文件中本来需要读入数字的地方放进了字符,比如文件a.txt里面有如下内容

1
2
4
abc
6
7

这里abc字符串就是错误的数据,然后打开文件和读入数据都要根据状态量来确定是读入错误还是正确还是到了文件末尾

program main
implicit none
integer(4):: n     ! each line the number to read
integer(4):: nLine ! which line of the file
integer(4):: iost1 ! file io state
integer(4):: iost2 ! file read state
character(len=100):: open_error_message ! the error message when opening a file
character(len=100):: read_error_message ! the error message when reading data
open_error_message = '文件打开错误'
read_error_message = '数据读入错误'
open(10, file='a.txt', status='old', action='read', iostat=iost1)
if(iost1.ne.0) then
    write(*,1000)open_error_message, iost1
1000 format(T1, A20,'IOSTAT=',I2)
else ! if read file successfully
    nLine = 0
    do
        read(10,*, iostat=iost2) n
    nLine = nLine + 1
    if(iost2.eq.0) then ! iost2=0时正常读入
        write(*,1001) nLine, n
        1001 format(T1,'From Line ', I2, ' read number', I10)
    elseif(iost2.gt.0)then ! 当数据读入错误时显示错误行号
        write(*,1002) nLine, read_error_message
        1002 format(T1,'Error In Line ',I2,' of the file:', A20)
        continue ! 并且继续读下一行
    elseif(iost2.lt.0)then ! 到了文件末尾就退出循环
        exit
    endif
    enddo
    close(10)!关闭文件
endif
end

这个例子的结果:

From Line  1 read number         1
From Line  2 read number         2
From Line  3 read number         4
Error In Line  4 of the file:数据读入错误
From Line  5 read number         6
From Line  6 read number         7

可见第四行数据格式有问题,就出现错误了,但不妨碍其他行的读入
如有帮助,还望题主给个宝贵的采纳支持答主答题哟,谢谢啦