8

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

3 に答える 3

4

はい、不可能です。position=書き込み位置を設定するだけです。通常、シーケンシャル ファイルへの書き込みによって、現在のレコード以降のすべてを削除するだけです。直接アクセス ファイルの最初のレコードを調整できる場合がありますが、最初に何かを追加するだけではありません。最初にコピーを作成する必要があります。

于 2013-10-25T08:03:13.870 に答える
0

フォーマットされていないデータを使用していて、予想される行数がわかっている場合は、直接アクセス ファイルの読み取り/書き込み方法を使用してみてください。これには、配列のように後でアクセスできる「レコード」に各行の情報を格納する可能性があります。

先頭に追加するには、ファイルの先頭にある「ヘッダー」の行と同じ数の空のレコードを作成してから、戻ってそれらの値を後で必要な実際の行に変更します。

Direct Access ファイル 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

コード ソースについては、「Direct Access Files」のセクションを参照してください: http://oregonstate.edu/instruct/ch590/lessons/lesson7.html

于 2014-11-19T15:27:50.890 に答える
-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
于 2014-10-17T07:10:56.367 に答える