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

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

问题描述

我有无序数据,我想将此数据按顺序写入文件.例如,该值的顺序为70,然后将此值写入文件的第70行.如何向前移动文件指针?

I have unordered data and I want to write this data to a file with an order. For example, the value's order is 70th, then this value is written to 70th line in the file. How can I move file pointer forward?

有没有像BACKSPACE这样的命令?

推荐答案

您还可以使用直接访问文件,在该文件中可以按顺序写入和读取记录.参见例如 http://en.wikipedia.org/wiki/Fortran_95_language_features#Direct- access_files

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

一天后

已建议使用顺序文件的解决方案.我认为这些方法不会起作用...请说明您是否知道如何使其起作用. (当然,您可以对内存中的值进行排序并按顺序将其写出.)以下是一些示例代码来说明问题.它创建了一个10行的文件,然后假设您要写入第5个值:

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

输出文件包含:

   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

更短而且更有效-输出文件包含十个数字,第五个数字从5更改为99.但是,它们是二进制的.

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天全站免登陆