写入文件,保留更改并附加到它们

Write to file, keep changes and append to them

我有一个为矩阵 u 创建值的程序,每次迭代都会更改 f,我想为每次迭代写出 u(2,2) 的值 f。例如 u(2,2)=5 f=1u(2,2)=9 f=2 等。

现在 test(u,n,f) 只写最后一个 value.When 它符合我停止 do 循环的条件。我不希望我的子例程每次都覆盖文件 plot.txt,我希望它在每次迭代时都保留 u(2,2)。我希望它看起来像这样

5  1

9  2

10 3

但它不仅写

15 25

如何解决这个问题?

subroutine test(u,n,f)

!input
integer :: n,f,write_unit
real(8) :: u(n+2,n+2)

!lokale
integer :: i,j
real(8) :: vek_x,vek_y


!Skriver vektor verdier til fil som gnuplot skal bruke
open(newunit=write_unit,access='sequential',file='plot.txt',status='unknown')

write(write_unit,*)'# x y vx vy'



vek_x=u(2,2)


!write(write_unit,*) vek_x,f

write(write_unit,*) vek_x,f
write(write_unit,*)''


close(write_unit,status='keep')

"Program" 为 u

创建不同的值
do f=1,1000

do j=2,n+1
  do i=2,n+1

u(i,j)=(u(i+1,j)+u(i-1,j)+u(i,j+1)+u(i,j-1))/4


!u(i,j)=(1-omega)*u(i,j)+omega*1/4*(u(i+1,j)+u(i-1,j)+u(i,j+1)+u(i,j-1))


  end do
end do



if (u(2,2) .eq. 15) then
exit
end if

call test(u,n,f)




end do

只需打开文件进行追加

open(newunit=write_unit,access='sequential',file='plot.txt',position='append',status='old',action='write')

如果这是你想要的。

第一次可能只想创建一个空的

open(newunit=write_unit,access='sequential',file='plot.txt',status='replace')
close(write_unit)