繁体   English   中英

程序无法写入FORTRAN中的文件

[英]Program failing to write to a file in FORTRAN

我一直在和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.

我相信您的错误来自以下事实:读取原始数组会使文件游标前进。 因此,当您写回文件时,光标已经经过数组。

我相信倒带(将光标设置到初始点)将纠正此问题:

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.

但是请注意,这将覆盖从文件开头开始的内容,因此,如果该文件中不仅包含数组,还将覆盖您的其他内容,也许会使输出看起来很奇怪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM