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

标签 loops file-io replace fortran

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

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

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

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

最佳答案

您的程序将执行 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

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

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

关于loops - 在 Fortran 中多次写入和替换文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19811323/

相关文章:

html - 使用正则表达式和 javascript 在 html 中突出显示单词 - 差不多了

Python 如何将嵌套的 for 循环放入函数中?

php - 如何从键返回 PHP 数组值?

java - 如何在 web-inf/class 下的类命名空间中创建/写入文件

c++ - 我正在尝试在某些条件下清除我的数据文件中的特殊字符,但不满足这些条件?

Java:用整数替换字符串

linux - sed 切片并在文件中追加行

c++ - Armadillo 中 SpMat<Type> 的迭代器是否只访问非零条目?

java - Android:如何检索解析的值

.net - 在 Linux 世界中是否有等同于 .Net FileSystemWatcher 的东西?