所以,假设我正在尝试在文件中读取我之前不知道的长度。我们可以在需要时使用iostat和while循环来中断,但是我遇到了一个问题。也就是说,我写的代码读取最后一行两次。我确信有一个明显的解决方案,但我似乎无法弄清楚。我不太了解read()或iostat函数是如何完全工作的(我在fortran中很新颖),但是我不能从文档中收集很多内容,所以我希望这里有人能够提供帮助。Fortran read()读取最后一行两次?
这里是(相关位)的代码,我已经写了:
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
然后输出从打印语句中的终端会是
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
请记住以下几点:这里的主要目的是能够读取一个文件e与任意数量的行。我对首先读取行数的解决方案不感兴趣。
感谢您的帮助!
更新好的我刚解决了这个问题。话虽如此,我想知道是否有一个解决方案比我的笨拙。这是我做过什么来解决这个问题
! 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