【发布时间】:2016-04-07 15:40:44
【问题描述】:
如果我使用 Fortran 以与流相同的方式写入和读取文件,则效果很好。如果我使用文本编辑器编辑文件而不更改任何内容(例如返回然后退格)并保存它不会读取的文件,在我希望它结束的位置之前引用文件结尾。
为了进行调查,我编写了以下代码,该代码写入了我的表格,然后一次将其作为一个字符读取到一个位置。只有当我正在读取的文件中没有新行时它才能正常工作。否则,我只会得到最后 n 个数字,n 是每行的数据量。
我们的想法是学习比顺序读取更强大的方法来读取我在工作中使用的来自工程软件和测试设备的大型格式奇怪的数据文件。
program stream
implicit none
character(len=1) :: text
integer(kind=4), dimension(100) :: array
integer(kind=4) :: status = 0, i
open (unit=11, file='out.txt', form='formatted', access='stream', action='readwrite', status='replace')
array = (/(i, i = 1,100)/) ! Populate vector from 1 to 100
write(unit=11,fmt='(10i4)') array ! Write array to file
i=0
do while ( status == 0) ! Read array back from file, one position at a time until end of file
i=i+1
read(unit=11, fmt='(a1)', pos=i, iostat=status) text
write(*,fmt='(a1)', advance='no') text ! Write results to screen to see what is in each position
end do
close(unit=11)
end program stream
File written then read:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Result: (many spaces here)
8 8 8 8 8 8 8 8 9 91 92 93 94 95 96 97 98 99 100
【问题讨论】:
-
PS,OSx 上的 gfortran,截至 1/2016 都是最新的
-
使用标签fortran,让更多人看到你的问题。仅当您想限制为单个版本(无 F 2008)时才使用这些版本。
标签: fortran