只需总结 cmets 和现有答案,您应该删除
'unformatted' 关键字在 open 语句中,因为 fortran 读取文本文件
作为您的data.txt 默认格式为一个。
假设您的文本文件可能如下所示:
1061 2.5 5.0 7.5 3.5
1062 9.0 2.5 10.0 7.5
1063 4.0 3.1 3.2 5
1064 2.1 1.9 ***** 7.8
1065 1.0 4.0 10.0 3.5
1066 4.4 1.9 2.5
1067 6.7 8.8 10.9 12.0
那么您应该在此之后处理不同的格式错误
最小的例子:
program FileIO
implicit none
character(256) :: line
character(80) :: msg
integer :: a,st
real :: b,c,d,e,f
open(10,file='data.txt')
do
write(*,'(A)') '------------------------------------------------------------'
read(10,'(A)',iostat=st) line ! Buffer input in line
write(*,'(A)') 'Reading of line '//trim(line)
if (st < 0) then ! End of file or end of record
exit
else
read(line,*,iostat=st,iomsg=msg) a,b,c,d,e
write(*,'(A)') 'IO-message is: '//trim(msg)
if (st == 0) then ! Read one line successfully
write(*,'(A)') 'Line successfully read: '//trim(line)
f=a+b+c+d+e ! Calculate result
else
write(*,'(A)') 'IO-error occured in line: '//trim(line)
f=0
endif
endif
end do
close(10)
end program FileIO
iostat 的否定结果表示文件结束或记录结束事件。 iostat 的肯定结果表示运行时错误消息,请参见例如对于Intel Fortran。
这应该由if 条件处理。
我建议您将文件输入缓冲在字符变量中,例如line。
它可以帮助您将错误生成行写回日志文件或标准
输出。
最小的例子生成这个输出:
------------------------------------------------------------
Reading of line 1061 2.5 5.0 7.5 3.5
IO-message is:
Line successfully read: 1061 2.5 5.0 7.5 3.5
------------------------------------------------------------
Reading of line 1062 9.0 2.5 10.0 7.5
IO-message is:
Line successfully read: 1062 9.0 2.5 10.0 7.5
------------------------------------------------------------
Reading of line 1063 4.0 3.1 3.2 5
IO-message is:
Line successfully read: 1063 4.0 3.1 3.2 5
------------------------------------------------------------
Reading of line 1064 2.1 1.9 ***** 7.8
IO-message is: list-directed I/O syntax error, unit -5, file Internal List-Directed Read
IO-error occured in line: 1064 2.1 1.9 ***** 7.8
------------------------------------------------------------
Reading of line 1065 1.0 4.0 10.0 3.5
IO-message is: list-directed I/O syntax error, unit -5, file Internal List-Directed Read
Line successfully read: 1065 1.0 4.0 10.0 3.5
------------------------------------------------------------
Reading of line 1066 4.4 1.9 2.5
IO-message is: end-of-file during read, unit -5, file Internal List-Directed Read
IO-error occured in line: 1066 4.4 1.9 2.5
------------------------------------------------------------
Reading of line 1067 6.7 8.8 10.9 12.0
IO-message is: end-of-file during read, unit -5, file Internal List-Directed Read
Line successfully read: 1067 6.7 8.8 10.9 12.0
------------------------------------------------------------
Reading of line 1067 6.7 8.8 10.9 12.0
第 1063 行的列表导向读取工作正常,即使数字 5 是
以整数形式提供给实变量e。行格式错误*****
正确检测到 1064 以及第 1066 行中缺少的数字。
请查看有关list-directed reading 的英特尔 Fortran 帮助,
如果您需要更多信息。
希望对你有帮助。