【发布时间】:2018-01-08 23:22:06
【问题描述】:
所以,假设我正在尝试读取一个我事先不知道其长度的文件。我们可以在需要时使用 iostat 和 while 循环来中断,但我对此有疑问。也就是说,我编写的代码读取了最后一行两次。我确信有一个明显的解决方案,但我似乎无法弄清楚。我不太了解 read() 或 iostat 函数是如何完全工作的(我对 fortran 很陌生),但我无法从文档中收集到太多信息,所以我希望这里有人能提供帮助。
这是我写的(相关的)代码:
filename = 'test.txt'
iostat_1 = 0
iostat_2 = 0
open(newunit = lun, file = filename, status = 'old', iostat = iostat_1)
if (iostat_1 == 0) then
do while(iostat_2 == 0)
if(iostat_2 == 0) then
read(lun,*,iostat = iostat_2) dum, real_1,real_2,int_1
print *, dum, real_1,real_2,int_1
endif
enddo
endif
所以,假设我的输入文件是
1 1.0 1.0 1
2 2.0 2.0 1
3 3.0 3.0 1
4 4.0 4.0 4
那么从 print 语句到终端的输出将会是
1 1.0 1.0 1
2 2.0 2.0 1
3 3.0 3.0 1
4 4.0 4.0 4
4 4.0 4.0 4
所以请记住以下几点:这里的主要目的是能够读取具有任意行数的文件。我对涉及首先读取行数的解决方案不感兴趣。
感谢您的帮助!
更新 好的,我刚刚解决了问题。话虽如此,我想知道是否有比我的更笨拙的解决方案。这是我为解决问题所做的工作
! Body of ReInsert
filename = 'rpriov3.dat'
iostat_1 = 0
iostat_2 = 0
open(newunit = lun, file = filename, status = 'old', iostat = iostat_1)
if (iostat_1 == 0) then
do while(iostat_2 == 0)
if(iostat_2 == 0) then
read(lun,*,iostat = iostat_2) dum, real_1,real_2,int_1
if(iostat_2 == 0) then !<---- Added this nested if statement
print *, dum, real_1,real_2,int_1
endif
print *, iostat_2
endif
enddo
endif
【问题讨论】: