gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:48:58 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com