从大小未知的文件中读取数组 [英] Reading an array from an unknown sized file
问题描述
我对Fortran 90并不陌生,但是我很好奇是否存在直接解决我的问题的方法。我有一个看起来像这样的文件:
I'm not new to Fortran 90, but I'm curious if a straightforward solution to my question exists. I have a file which looks like this:
1
2
3
...
n
其中 n
可以是任何整数,我想将文件中的每个数字读入整数数组 A
。换句话说, A =(1,2,3,...,n)
。在运行代码之前,我不知道n有多大。我的解决方案是打开文件,从文件中读取所有内容,找到n,然后分配A(n)
,然后重新读取文件:
where n
could be any integer and I want to read each number in the file into an integer array A
. In other words, A=(1,2,3,...,n)
. I don't know how big is n before running the code. My solution was to open the file, read everything from it, find n, then allocate A(n)
and then reread the file:
read(unit=20,fmt=*,iostat=io) a
if (io/=0) exit
A(i)=a
但是,仅出于优雅的目的,可以避免这种重复阅读吗?
But, just for the sake of elegance, could this double reading be avoided?
推荐答案
以下是一个非常简单的链接列表的示例:
Here is an example of a very simple linked list:
module list_mod
implicit none
type list_int
integer :: val = 0
integer :: length = 0
type(list_int), pointer :: next => NULL()
type(list_int), pointer :: tail => NULL()
end type
contains
subroutine append( list, val )
type(list_int), intent(inout) :: list
integer :: val
if ( associated(list%next) ) then
allocate( list%tail%next )
list%tail => list%tail%next
else
allocate( list%next )
list%tail => list%next
endif
list%tail%val = val
list%length = list%length + 1
end subroutine
end module
您可以使用它来逐项读入文件。列表的长度随每个项目的增加而增加。此信息用于分配一个数组,然后按文件顺序分配数组。
You can use this to read in the file entry by entry. The length of the list is incremented with each item appended. This information is used to allocate an array which is then file element-wise.
program test
use list_mod
implicit none
type(list_int) :: ilist
type(list_int), pointer :: cur
integer,allocatable :: array(:)
integer :: i, io
open( unit=20, file="test.txt", status='old' )
do
read(unit=20,fmt=*,iostat=io) i
if (io/=0) exit
call append(ilist, i)
enddo
allocate( array( ilist%length ) )
cur => ilist%next
i = 1
do while (associated(cur))
array( i ) = cur%val
i = i + 1
cur => cur%next
enddo
print *,array
end program
这篇关于从大小未知的文件中读取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!