2013-10-25 243 views
8

我有一個由Fortran程序(格式化)編寫的現有文件,我想在文件的開頭添加幾行。這個想法是在沒有複製原始文件的情況下這樣做的。在現有文件中寫入而不覆蓋Fortran

我可以在與該文件的末尾添加一行:

open(21,file=myfile.dat,status='old',action='write', 
     form='formatted',position="append") 
write(21,*) "a new line" 

,但是當我嘗試:

open(21,file=myfile.dat,status='old',action='write', 
     form='formatted',position="rewind") 
write(21,*) "a new line" 

它將覆蓋整個文件。

這可能是不可能的。 至少,我很樂意確認這是不可能的。

回答

4

是的,這是不可能的。用position=你只能設置寫作的位置。通常,您只需通過在順序文件中寫入來刪除當前記錄之後的所有內容。您可以在一個直接訪問文件的開始處調整記錄,但不能在開始時添加一些內容。你必須先複製一份。

+0

但你不必讀取整個舊的文件到內存一旦。使用操作系統將舊文件重命名爲臨時文件名。然後使用舊文件名創建一個新文件,然後輸入所需的數據。然後將舊文件附加到新文件。 (根據操作系統和文件數據的性質,您可能可以在操作系統上執行該操作。) – dmm

+0

「先製作副本」也包括您的情況。 –

-1

這是可能的!這是一個可以完成任務的示例程序。

! Program to write after the end line of a an existing data file 
    ! Written in fortran 90 
    ! Packed with an example 

    program write_end 
    implicit none 
    integer :: length=0,i 

    ! Uncomment the below loop to check example 
    ! A file.dat is created for EXAMPLE defined to have some 10 number of lines 
    ! 'file.dat may be the file under your concern'. 


    !  open (unit = 100, file = 'file.dat') 
    !  do i = 1,10 
    !  write(100,'(i3,a)')i,'th line' 
    !  end do 
    !  close(100) 

    ! The below loop calculates the number of lines in the file 'file.dat'. 

    open(unit = 110, file = 'file.dat') 
    do 
     read(110,*,end=10) 
     length= length + 1 
    end do 
    10 close(110) 

    ! The number of lines are stored in length and printed. 

    write(6,'(a,i3)')'number of lines= ', length 

    ! Loop to reach the end of the file. 

    open (unit= 120,file = 'file.dat') 
    do i = 1,length 
     read(120,*) 
    end do 

    ! Data is being written at the end of the file... 

    write(120,*)'Written in the last line,:)' 
    close(120) 
    end 
+0

他想要在文件的**開頭**寫入。爲了寫作,只需使用'position = append'。 –

+0

謝謝,我沒有正確地閱讀這個問題。永遠不會再發生。 我不知道position = append, 之間有什麼區別,但access ='append',status ='old'也可以, – Sathyam

+0

'access = append'是一些奇怪的非標準擴展。標準的,Fortran 90是'position = append' –

0

如果您正在使用未格式化的數據並知道需要多少行,請嘗試使用直接訪問文件讀/寫方法。這有可能將每行的信息存儲在「記錄」中,以後可以像數組一樣訪問該記錄。

爲了追加到開頭,只需創建儘可能多的空記錄,因爲您在文件開頭的「標題」中會有行,然後返回並將其值更改爲您希望它們的實際行後來。直接訪問文件IO的

例子:

CHARACTER (20) NAME 
INTEGER I 
INQUIRE (IOLENGTH = LEN) NAME 
OPEN(1, FILE = 'LIST', STATUS = 'REPLACE', ACCESS = 'DIRECT', & 
     RECL = LEN) 

DO I = 1, 6 
    READ*, NAME 
    WRITE (1, REC = I) NAME    ! write to the file 
END DO 

DO I = 1, 6 
    READ(1, REC = I) NAME    ! read them back 
    PRINT*, NAME 
END DO 

WRITE (1, REC = 3) 'JOKER'   ! change the third record 

DO I = 1, 6 
    READ(1, REC = I) NAME    ! read them back again 
    PRINT*, NAME 
END DO 

CLOSE (1) 
END 

源代碼,請參見「直接訪問文件」部分: http://oregonstate.edu/instruct/ch590/lessons/lesson7.html

相關問題