How to write data to specific line in the file in Fortran?
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?
Is there any command like 开发者_开发问答BACKSPACE
?
As you're talking about lines and backspace, presumably you mean access="sequential" and form="formatted".
In that case, in order to skip a record forward, you can do just an empty read, e.g.
read(unitnum, *)
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.
For each data entry, use method described by janneb to get to a desired line. Then use REWIND statement to go back to the beginning of the file (access='sequential' only).
Also in case you need it, look up format descriptors to see how to move left/right along a single line.
精彩评论