在现有文件中写入而不在Fortran中重写

在现有文件中写入而不在Fortran中重写,fortran,overwrite,Fortran,Overwrite,我有一个由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'

我有一个由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"
它覆盖了整个文件

这可能是不可能的。
至少,我很高兴能确认这实际上是不可能的。

是的,这是不可能的。使用
position=
只设置写入的位置。通常,您只需通过写入顺序文件来删除当前记录之外的所有内容。您可以在直接访问文件的开头调整记录,但也不能仅在开头添加内容。你必须先复印一份。

这是可能的!!!下面是一个可以完成此任务的示例程序

   ! 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

如果您使用的是未格式化的数据,并且知道需要多少行,请尝试使用直接访问文件读/写方法。这有可能将每一行的信息存储在一个“记录”中,以后可以像数组一样访问该记录

为了附加到开头,只需创建尽可能多的空记录,就可以在文件开头的“头”中添加行,然后返回并将其值更改为您希望稍后添加的实际行

直接访问文件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
源代码,请参阅“直接访问文件”部分:

但您不必一次将整个旧文件读入内存。使用操作系统将旧文件重命名为临时文件名。然后使用旧文件名创建一个新文件,并输入所需的数据。然后将旧文件附加到新文件。(根据操作系统和文件数据的性质,您可能可以使用操作系统来执行此操作。)“先复制”也包括您的情况。他希望在文件的开头写入。谢谢你,我没有正确阅读这个问题。再也不会发生了。我不知道position=append之间是否有任何区别,但是access='append',status='old'也可以
access=append
是一种奇怪的非标准扩展。标准,Fortran 90是
position=append