簡體   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