递归地输入输入文件以进行操作

时间:2015-03-11 09:30:15

标签: fortran fortran90 gfortran fortran95

我有几个输入数据文件,名称为angleFile1.dat,angleFile2.dat,angleFile3.dat等。 (我有超过100个文件)

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

我编写了一个Fortran代码,一次完成一个文件的工作。

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

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)并在同一输出文件中写入分发?

非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

好吧,一种方法是将读数分成单独的子程序。像(未经测试)的东西:


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

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