main.f90:
program main
use misc
implicit none
integer :: ival
integer :: iarr(3)
call get_param('param.in', 'ics', 1, ival)
!call get_param('param.in', 'ics', 1, ival, 0)
print *, ival
call get_param('param.in', 'arr', 2, ival, ndim=3, iarr=iarr )
print *, iarr
end program
misc.f90
module misc
implicit none
contains
subroutine get_param(fname, varname, vartype, ivalue, ndim, iarr)
implicit none
character(*),intent(in) :: fname
character(*),intent(in) :: varname
integer,intent(in) :: vartype
integer,intent(out) :: ivalue
integer,optional,intent(in) :: ndim
integer,optional,intent(out) :: iarr(10000)
integer :: lvarname1, len_str, loc
character(len=300) :: varname1, varname2, line_str, val_str
varname1 = trim(adjustl(varname))
lvarname1 = len_trim(varname1)
open(15, file=fname, action='read', status='old')
do
read(15,'(a)',end=99) line_str
line_str = trim(adjustl(line_str)) !place blanks at end
len_str = len_trim(line_str)
if(len_str == 0) cycle
loc = index(line_str, '=')
varname2 = trim(line_str(1:loc-1)) !varname
if(varname1 == varname2) then
val_str = line_str(loc+1:len_str)
if(vartype == 1) then !integer
read(val_str,*) ivalue
else !integer array
if(.not. present(ndim)) stop 'get_param: ndim not found'
if(.not. present(iarr)) stop 'get_param: iarr not found'
if(ndim > 10000) stop 'get_param: ndim > 10000'
read(val_str,*) iarr(1:ndim)
endif
exit
endif
enddo
99 close(15)
end subroutine get_param
end module misc
param.in:
ics = 2
arr = 1 2 3
(1) Compile misc.f90 and main.f90 with option -O1 using pgfortran 19.10
pgfortran -O1 misc.f90 main.f90
then run ./a.out, gives correct result:
2
1 2 3
(2) Compile misc.f90 and main.f90 with option -O using pgfortran 19.10
pgfortran -O misc.f90 main.f90
then run ./a.out, Segmentation fault (core dumped)