Program failing to write to a file in FORTRAN

I've been messing around with FORTRAN a bit and decided to write a simple Blackjack program, keeping win/loss statistics inside a file. Thing is, every time I execute the program, it writes a new array rather than overwriting the existing one in the file.

Relevant pieces of code:

open(15, file='placar.dat')            !opens the file containing a (0,0,0,0) array
integer, dimension(1:4)::round=0'      !This is the array which contains the stats for a 
subroutine r(v)                        !given round, e.g.: player 1 wins and player
integer, intent(in),dimension(1:4)::v  !2 loses, round(1)=1, 
integer, dimension(1:4)::vx            !round(2)=0, round(3)=0, round(4)=1
read(15,*)vx                           !This line reads the array contained in the file to 
                                       !the array vx.
do i=1,4,1
     vx(i)=vx(i)+v(i)                  !this will add the round statistics passed to this 
end do                                 !subroutine to the vx array.
write(15,*)(vx(i),i=1,4)               !this line should overwrite the old array contained
end subroutine r                       !in the file with the new values. But this does not 
                                       !happen and a new line is written.

Upvotes: 0

Views: 208

Answers (1)

River
River

Reputation: 9093

I believe your error comes from the fact that reading in the original array advances the file cursor. Thus when you write back to the file, your cursor is already past the array.

I believe rewinding (setting cursor to initial point) the file would rectify this:

open(15, file='placar.dat')            !opens the file containing a (0,0,0,0) array
integer, dimension(1:4)::round=0'      !This is the array which contains the stats for a 
subroutine r(v)                        !given round, e.g.: player 1 wins and player
integer, intent(in),dimension(1:4)::v  !2 loses, round(1)=1, 
integer, dimension(1:4)::vx            !round(2)=0, round(3)=0, round(4)=1
read(15,*)vx                           !This line reads the array contained in the file to 
                                       !the array vx.
do i=1,4,1
     vx(i)=vx(i)+v(i)                  !this will add the round statistics passed to this 
end do                                 !subroutine to the vx array.
rewind(15)                             !rewind file
write(15,*)(vx(i),i=1,4)               !this line should overwrite the old array contained
end subroutine r                       !in the file with the new values. But this does not 
                                       !happen and a new line is written.

Note however, that this will overwrite content starting from the beginning of your file, so if you have more than just the array in that file, it will overwrite your other content, perhaps in a way that makes the output look quite odd.

Upvotes: 1

Related Questions