我一直在搞乱FORTRAN,并决定编写一个简单的Blackjack程序,将赢/输统计保存在文件中。事实上,每次执行程序时,它都会写一个新数组,而不是覆盖文件中现有的数组。
相关的代码:
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.
答案 0 :(得分:1)
我相信你的错误来自于原始数组中的读取会使文件光标前进。因此,当您回写文件时,光标已经过了数组。
我相信倒带(将光标设置到初始点)文件会纠正这个:
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.
但请注意,这将覆盖从文件开头开始的内容,因此如果您不仅仅是该文件中的数组,它将覆盖您的其他内容,可能会使输出看起来很奇怪