Fortran - 如何将数据写入文件中的特定行? [英] Fortran - How to write data to specific line in the file?

查看:968
本文介绍了Fortran - 如何将数据写入文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我的问题是我有无序的数据,我想用订单把这些数据写入文件。例如,值的顺序是第70个,那么这个值被写入文件的第70行。如何向前移动文件指针。是否有像BACKSPACE这样的命令。

解决方案

您也可以使用直接访问文件,其中可以写入和读取记录没有秩序。例如,参见 http://en.wikipedia.org/wiki/Fortran_95_language_features#Direct- access_files



在一天后编辑:



建议使用顺序文件的解决方案。我不认为这些会起作用......请解释一下,如果你知道如何使它工作。 (当然,您可以对内存中的值进行排序,然后依次写出它们。)下面是一些示例代码来说明问题。它创建一个10行的文件,然后假设你想写第5个值:

  program test_rewind 

integer :: i,j


open(unit = 15,file =test_rewind.txt,access =sequential,form =formatted,action = readwrite)

do i = 1,10
write(15,'(I4)')i
end do

倒带(15)

do i = 1,4
read(15,*)j
end do

write(15,'(I4)')99

stop

end program test_rewind

输出文件包含:

  1 
2
3
4
99

顺序文件的问题在于,写入现有文件会在该点后擦除所有内容。 p>

与直接访问解决方案相比:

 程序test_rewind 

integer :: i

open(unit = 15,file =test_rewind.dat,acce ss =direct,form =unformatted,action =readwrite,recl = 4)

do i = 1,10
write(15,rec = i) b $ b end do

write(15,rec = 5)99

stop

end program test_rewind

更短并且工作正常 - 输出文件包含十个数字,第五个数字从5改为99.然而,它们是二进制的。 p>

Hi my problem is that I have unordered data, I want to write these data to a file with an order. For example, value's order is 70th, then this value is written to 70th line in the file. How can I move file pointer forward. Is there any command like BACKSPACE.

解决方案

You can also use a direct access file, in which the records can be written and read out of order. See, for example, http://en.wikipedia.org/wiki/Fortran_95_language_features#Direct-access_files

Edit after one day:

Solutions using a sequential file have been suggested. I don't think these will work ... please explain if you know how to make it work. (Of course, you can sort the values in memory and write them out sequentially.) Here is some sample code to illustrate the problem. It creates a file of 10 lines, then supposes that you want to write the 5th value:

program test_rewind

   integer :: i, j


   open (unit=15, file="test_rewind.txt", access="sequential", form="formatted", action="readwrite" )

   do i=1,10
      write (15, '(I4)') i
   end do

   rewind (15)

   do i=1,4
      read (15, *) j
   end do

   write (15, '(I4)') 99

   stop

end program test_rewind

The output file contains:

   1
   2
   3
   4
  99

The problem for the sequential file is that a write to an existing file erases everything after that point.

Compare to the direct access solution:

program test_rewind

   integer :: i

   open (unit=15, file="test_rewind.dat", access="direct", form="unformatted", action="readwrite", recl=4 )

   do i=1,10
      write (15, rec=i) i
   end do

   write (15, rec=5) 99

   stop

end program test_rewind

Shorter and it works -- the output file contains ten numbers with the 5th changed from 5 to 99. However, they are binary.

这篇关于Fortran - 如何将数据写入文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆