从文件到数组读取整数?

时间:2017-03-31 16:45:33

标签: arrays file-io fortran

尝试将10个以空格分隔的整数值从文件读取到数组中:

subroutine ReadFileIntoArray (filename, int_array)
    implicit none

    character(len = *), intent (in) :: filename
    integer, dimension(:), intent(in out) :: int_array

    integer :: current_index

    open (1, file = filename, status = 'old')

    do current_index = 1, 10, 1
        read(1, *) int_array(current_index)
    end do

    close (1)
end subroutine ReadFileIntoArray

! ---------------------------------------------------------------------- !

program ReadFileCalculateAverage
    implicit none

    integer, dimension(10) :: int_array
    character (len = 9) :: filename = 'makrs.txt'

    call ReadFileIntoArray(filename, int_array) ! <--- error line

end program ReadFileCalculateAverage

我获得(在Windows 10上使用Code :: Blocks 16.01)的错误是:

Error: explicit interface required for 'ReadFileIntoArray' : assumed-shape argument

考虑到我对Fortran的了解有限,纠正上述代码的方法是什么?是否还有其他重要的(仍然未被观察到的)错误我应该纠正?

1 个答案:

答案 0 :(得分:1)

对于打开和读取,您最终需要1以外的单位数。也许是21或使用NEW UNIT。

对于FileName,我通常在任何地方使用LEN = 256,然后在打开时使用

INTEGER :: LUN
...
OPEN(NEWUNIT=LUN, FileName(1:LEN_TRIM(FileName)) )

另一种选择是在具有子例程的模块中声明FileName,并且不要传递它

MODULE AA
IMPLICIT NONE
CHARACTER(LEN=256), PUBLIC :: FileName
CONTAINS
subroutine readarray(array)
...
ENDMODULE AA

或者为*

提供一些东西
SUBROUTINE readarray(FileName,array,lenF)
iNTEGER,INTENT(IN   )           :: LenF
CHARACTER(LEN=LenF), INTENT(IN) :: FileName