在 Fortran 中多次写入和替换文件

jsh*_*hep 4 file-io fortran loops replace

我正在尝试运行一个需要特别长时间的代码。为了完成它,我将时间步循环分开,以便可以转储数据,然后为下一个循环重新读取:

do 10 n1 = 1, 10
  OPEN(unit=11,file='Temperature', status='replace')
  if (n1.eq.1) then
    (set initial conditions)
  elseif (n1.gt.1) then
  READ(11,*) (reads the T values from 11)
  endif

  do 20 n = 1, 10000
    (all the calculations for new  T values)
    WRITE(11,*) (overwrites the T values in 11 -  the file isn't empty to begin with)
20    continue

10    continue
Run Code Online (Sandbox Code Playgroud)

我的问题是,这仅适用于 2 次 n1 时间步 - 在它替换文件 11 一次后,它不再替换并只是重申其中的值。

open语句有问题吗?有没有办法可以在同一代码中多次替换文件 11?

Hig*_*ark 5

您的程序将执行该open语句 10 次,每次使用status = 'replace'. 在第一轮可能文件不存在时,该open语句导致创建一个新的空文件。在第二次循环中,该文件确实存在,因此该open语句会导致该文件被删除并创建一个新的、空的同名文件。任何读取该文件的尝试都可能导致问题。

我会将初始文件从循环中取出并按照以下几行重构代码:

open(unit=11,file='Temperature', status='replace')
(set initial conditions)
(write first data set into file)

do n1 = 2, 10
  rewind(11)
  read(11,*) (reads the T values from 11)
  ! do stuff
  close(11)   ! Not strictly necessary but aids comprehension of intent
  ! Now re-open the file and replace it
  open(unit=11,file='Temperature', status='replace')
  do n = 1, 10000
      (all the calculations for new  T values)
      write(11,*) (overwrites the T values in 11 -  the file isn't empty to begin with)
  end do
end do
Run Code Online (Sandbox Code Playgroud)

但是还有许多其他方法可以重构代码;选择一款适合您的。

顺便说一下,通过写入/读取文件将数据从一个迭代传递到下一个迭代可能非常慢,我只会将它用于检查点以支持重新启动失败的执行。