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

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

为了追加到开头,只需在文件开头的“标题”中创建尽可能多的空记录,然后返回并将它们的值更改为您希望它们稍后出现的实际行。

直接访问文件 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

于 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 回答