Title: Write to file, keep changes and append to them
Tags: fortran;fortran90;gfortran
Question: I have a program that creates values for the matrix ```u```, and this changes for every iteration ```f```, I want to write out the value of ```u(2,2)``` for every iteration ```f```. So for example ```u(2,2)=5  f=1```,   ```u(2,2)=9  f=2```, and so on.

Now ```test(u,n,f)``` only writes the last value.When it have met my criteria to stop the do loop. I don't want my subroutine to overwrite the file plot.txt every time, I want it to keep ```u(2,2)``` for every iterations. I want it to look like this

```5  1

9  2

10 3
```

but not it only writes

```15 25
```

How can this be fixed?

```subroutine test(u,n,f)

!input
integer 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 n,f,write_unit
real(8) 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 u(n+2,n+2)

!lokale
integer 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 i,j
real(8) 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 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" that creates different values for ```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
```


Here is the accepted answer: Just open the file for appending

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

if that is what you wanted.

For the first time to may want to just create it empty

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



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:10/11/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<fortran><fortran90><gfortran>', 'Title': 'Write to file, keep changes and append to them', 'ViewCount': 709, 'id': 39983097, 'user_AboutMe': None, 'user_AccountId': 7908946.0, 'user_DisplayName': 'ursmooth', 'user_Reputation': 311.0, 'user_Views': 40.0, 'user_id': 5973557.0}}