我如何在Fortran中创建一个功能,该功能可以从文件读取并使用该功能

问题描述

我有一堆文件,其中包含行号。我需要写一个函数

  1. 第一次从文件中读取文件中的元素数量
  2. 分配一个数组,并将文件中的数字读入数组;
  3. 返回一个数组 我的函数获取一个字符串-文件名-作为输入。

所以,我写的函数是:

function arrays_proc(name) result(arr)
    character(len=128),intent(in)              :: name
    integer                                     :: i,tmp,ios
    character(len=30)                           :: line
    double precision,dimension(:),allocatable :: arr

    open(unit=09,file=name,status='old',iostat=ios)
    if ( ios /= 0) stop "error opening file"
    tmp = 0

    do
        read(09,'(A)',iostat=ios) line
        if (ios /= 0) exit
        tmp = tmp + 1
    end do

    allocate(arr(tmp))

    rewind(09)
    do i=1,tmp
        read(09,'(A)') arr(i)
    end do
    close(09)
    return
end function arrays_proc

然后,在我编写的主程序中

...
real(8),allocatable  :: points,potent
points = arrays_proc(trim('carbon_mesh.txt'))
potent = arrays_proc(trim('carbon_pot.txt'))
...

运行程序时,我立即得到“错误打开文件”。 我认为问题出在文件名或如何将它们放入函数中。 无论如何,我希望有人能帮助我

解决方法

使用最少的program编译代码时,GFortran会显示以下警告:

a.f90:4:25:

    4 |     points = arrays_proc(trim('carbon_mesh.txt'))
      |                         1
Warning: Character length of actual argument shorter than of dummy argument ‘name’ (15/128) at (1)
a.f90:5:25:

    5 |     potent = arrays_proc(trim('carbon_pot.txt'))
      |                         1
Warning: Character length of actual argument shorter than of dummy argument ‘name’ (14/128) at (1)

尝试在name中打印arrays_proc的值表明该值充满了垃圾。因此,在警告的引导下,您可以尝试将name参数的长度更改为*,以允许将任意长度的字符串用作输入。

进行此更改后,该功能将设法打开文件。

另请参阅:Passing character strings of different lengths to functions in Fortran