递归地接受输入文件进行操作

recursively take in input file for operation

我有几个名称为 angleFile1.dat、angleFile2.dat、angleFile3.dat 等的输入数据文件。 (我有100多个文件)

每个文件包含45000个角度数据。我想将这些角度分组以获得 0 到 360 度范围内的分布。

我已经编写了一个 Fortran 代码来一次处理一个文件。

此代码将读取输入文件 "angleFile1.dat" 并在 "angleOut.dat" 文件中写入分布(在 bin 中)。

program binangle
implicit none

integer :: i, j, k
integer,parameter :: arr=45000

real,dimension(1:arr) :: aangle
integer,dimension(0:360) :: binaangle

do i = 0,360
 binaangle(i) = 0.0
end do

 !OPEN OUTPUT FILE
open(unit=49,status="unknown",file="angleOut.dat")

 !OPEN INPUT FILE
open(unit=50,status="unknown",file="angleFile1.dat")
read(50,'(F8.3)') (aangle(i), i = 1,arr)


! DO THE BINNING    
do j = 1, arr
        binaangle(int(aangle(j))) = binaangle(int(aangle(j))) + 1
end do


! WRITE INTO OUTPUT FILE    
do k = 0,360
write(49,*) k, "    ", binaangle(k)
end do

如何使此代码递归地接收输入文件(angleFile1.dat、angleFile2.dat、angleFile3.dat 并说直到 angleFile100.dat)并将分布写入相同的输出文件?

非常感谢您的帮助。

好吧,一种方法是将阅读分成一个单独的子例程。像(未经测试):


program binangle
implicit none

integer :: i, k
integer,parameter :: nfiles = 100 ! Use get_command_argument to read the
                                  ! value at runtime rather than hardcoded,
                                  ! left as an exercise to the reader

integer,dimension(361) :: binaangle

binaangle = 0 ! Use array op rather than manual loop

do i = 1, nfiles
  call add_angles_to_bins(binaangle, i)
end do

!OPEN OUTPUT FILE
open(unit=49,status="replace",file="angleOut.dat")

! WRITE INTO OUTPUT FILE    
do k = 1, ubound(binaangle, 1)
  write(49,*) k - 1, "    ", binaangle(k)
end do

contains
subroutine add_angles_to_bins(bins, fnum)
  integer, intent(inout) :: bins(:)
  integer, intent(in) :: fnum
  character(len=200) :: fname
  integer, parameter :: arr = 45000
  real :: aangle(arr)
  write(fname, '(A,I0,A)') 'angleFile', fnum, '.dat'
  !OPEN INPUT FILE
  open(unit=50,status="old",file=fname)
  read(50,'(F8.3)') aangle
  close(50)
  ! DO THE BINNING    
  do j = 1, arr
    binaangle(int(aangle(j)) + 1) = binaangle(int(aangle(j)) + 1) + 1
  end do
end program binangle

(有人可能会补充说,上面建议的解决方案不使用递归。)