开发者

Read a line containing (large) N reals to an array in Fortran

开发者 https://www.devze.com 2023-01-07 09:39 出处:网络
I\'ve read() down past a header of an input file, and read the value of L on the way. Now I come to a line of L^2 consecutive reals, which I need to input to the elements of an allocatable array A(L,

I've read() down past a header of an input file, and read the value of L on the way.

Now I come to a line of L^2 consecutive reals, which I need to input to the elements of an allocatable array A(L,L).

Trying

          character *100 :: buffer
          read (1,10) buffer
10      format(a(L*10))

results in

Error: Syntax error in FORMAT statement at (1)  
Error: FORMAT label 10 at (1) not defined

but I'm not sure how else to deal with a (hugely) variable number of reals.

Trying:

    do i=1,L
    do j=i,L
        read (1,"(f10.7)") buffer
        read (buffer,*) A(i,j)
    enddo
    enddo

throws:

Fortran runtime error: Expected REAL for item 2 in formatted transfer, got CHARACTER
    (开发者_开发百科f10.7)

I can't simply read(1,"(a1000)") as L will eventually end up huge, so what I really need is a way to parse the elements one by one.

Please say there's a way?


After you have processed the header, perhaps by doing "fancy" things by reading it into a string and parsing the string, why not just directly read the numbers from the file and skip the character "buffer"?

"read (unit, *) A" is called "list-directed IO" -- if you want to know what to search for or look up -- it seems like a good approach to me. It is very flexible -- you don't have to be concerned with precisely aligning you numbers into columns. If you just read into the array "A", the elements will be read in Fortran array element order.

In Fortran 2003, you can use "*" as a variable format repeat specifier: read (unit, '( *(F10.7) )' ). However, not many compilers support this yet. This easiest thing to do is just to use a huge value, larger than you will ever need -- the read will stop when there are no more items on the list to be read -- the repeat specifier is allowed to exceed the number of items read.


Is this what you were looking for?

http://www.tek-tips.com/viewthread.cfm?qid=1420862&page=1

Update:

http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap05/format.html http://rainbow.ldgo.columbia.edu/data/fortranreaddata.html

This goes over unformatted record-length reading. It's been a long time since I've had to mess with fortran I/O. I'm pretty certain there's a flag to either OPEN or READ that specifies that it shouldn't continue onto the next line, but rather keep the file pointer in place so that the next READ can start from there. But I can't remember it off-hand...


Haha, this seems to work:

read (1,*) A
write (*,*) A

Seems the standard knows what it's doing, even if I don't.

0

精彩评论

暂无评论...
验证码 换一张
取 消