我创建了一个fortran代码来计算cfd模型的温度。在稳态模拟的每次迭代中都会调用此代码并计算温度。在每次调用我的代码/迭代时,我希望我的fortran代码也将温度字段保存在txt文件中并保存。计算温度字段并将值保存在TFIELD(100; 1:6)后,保存在txt文件中的部分如下所示:
OPEN(UNIT=35,FILE='W:\temperaturField.txt',
&FORM ='FORMATTED',STATUS='UNKNOWN',
&ACTION='READWRITE')
WRITE (35,FMT='5(F8.3,2X))') TFIELD(100,1:6)
使用此代码,它只会在每次迭代时覆盖我的txt文件的第一行。但我想将每个TFIELD(100,1:6)数组粘贴到一个新行上。我怎么能这样做?
答案 0 :(得分:1)
添加POSTITION =' APPEND'开放:
OPEN(UNIT=35,FILE='W:\temperaturField.txt',
&FORM ='FORMATTED',STATUS='UNKNOWN',POSITION='APPEND',
&ACTION='READWRITE')
答案 1 :(得分:0)
您似乎在为每次迭代打开和关闭文件。如果你需要调试,这是一种快速而肮脏的方法,但速度很慢。
如果你想这样做,你可能想要做@Jack所说的:在POSITION='APPEND'
语句中加入OPEN
来设置将数据写入文件末尾的位置。此外,您需要确保每次都关闭它。
更好(更有效)的方法是保持文件一直打开。我是用模块做的:
module temp_writer_module
implicit none
integer :: temp_writer_unit
logical :: is_opened = .FALSE.
private :: temp_writer_unit, is_opened
contains
subroutine temp_writer_open()
integer :: ios
character(len=100) :: iomsg
if (is_opened) then
print*, "Warning: Temperature file already openend"
return
end if
open(newunit=temp_writer_unit, file='W:\temperatureField', &
form='FORMATTED', status='UNKNOWN', action='WRITE', &
iostat=ios, iomsg=iomsg)
if (ios /= 0) then
print*, "Error opening temperature file:"
print*, trim(iomsg)
STOP
end if
is_opened = .TRUE.
end subroutine temp_writer_open
subroutine temp_writer_close()
if (.not. is_opened) return
close(temp_writer_unit)
is_opened = .FALSE.
end subroutine temp_writer_close
subroutine temp_writer(temps)
real, intent(in) :: temps(6)
integer :: ios
character(len=100) :: iomsg
if (.not. is_opened) call temp_writer_open()
write(temp_writer_unit, *, iostat=ios, iomsg=iomsg) temps
if (ios /= 0) then
print*, "Error writing to temperature file:"
print*, trim(iomsg)
end if
end subroutine temp_writer
end module temp_writer_module
然后你可以在你的程序中使用它:
subroutine calc_temps(...)
use temp_writer_module
<variable declarations>
<calculations>
call temp_writer(tfield(100, 1:6))
end subroutine calc_temps
在程序结束之前,不要忘记调用temp_writer_close
例行程序。