问题描述
所以,我写的函数是:
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