简体   繁体   中英

Reading columns from data file in fortran

I wrote the following block to read from an external data file:

     open(unit=338,file='bounnodes.dat',form='formatted') 
      DO I=1,NQBOUN
         DO J=1,NUMBOUNNODES(I)
            read(338,2001) NODEBOUN(i,j)
            write(6,*) 'BOUNDARY NODES',  NODEBOUN(i,j)
         ENDDO
       ENDDO
     2001
     FORMAT(32I5)

As far as I understood, this should read a 2 x 32 array from bounnodes.dat . However, I get an error end-of-file during read and it prints the first column.

I tried to read a 32 x 2 array using the same code, and it reads 32 elements of the first column, but outputs 0s for the next column.

Can you please explain what is happening? Is my formatting wrong?

Every read statement in Fortran advances to the next record. This means a new line in normal text files. Try this:

   DO I=1,NQBOUN
     DO J=1,NUMBOUNNODES(I)
        read(338,2001,advance='no') NODEBOUN(i,j)
        write(*,*) 'BOUNDARY NODES',  NODEBOUN(i,j)
     ENDDO
     read(338,*)
   ENDDO

where NQBOUN is number of rows and NUMBOUNNODES(I) is number of columns in a row. (I have allway problems, what is 32x2 vs. 2x32)

You can make it even shorter, using the implied do

   DO I=1,NQBOUN
        read(338,2001) ( NODEBOUN(i,j) , j=1,NUMBOUNNODES(I) )
        write(*,*) ( 'BOUNDARY NODES', NODEBOUN(i,j) , j=1,NUMBOUNNODES(I) )
   ENDDO

or even

   DO I=1,NQBOUN
        read(338,2001) NODEBOUN(i,:)
        write(*,*) 'BOUNDARY NODES',  NODEBOUN(i,1:NUMBOUNNODES(I))
   ENDDO

All of these use Fortran 90 features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM