2

How do I read only every tenth set of lines in a large file? A simple example is shown below. I thought I could use the increment for the do loop, but it seems that only changes the index T below, but does not skip over the desired set of lines.


IMPLICIT NONE
INTEGER :: T
REAL(8) :: RR,RS,RT

OPEN(UNIT=11,FILE='test.dat',STATUS='UNKNOWN',ACTION='READ')

DO T = 1,1000,10

   READ(11,*) RR
   READ(11,*) RS
   READ(11,*) RT

ENDDO

CLOSE(11)

END PROGRAM TRACE
user2
  • 71
  • 1
  • 6

1 Answers1

0

You have written a loop whose skip is independent of the skip over the rows of the input file. You need to connect the two, like the following code,

use iso_fortran_env, only: RK => real64, IK => int32
integer(IK)  :: i, fileUnit, iostat
real(RK) :: Data(3)

! write data to file

open(newunit = fileUnit, file = "temp.txt")
write(fileUnit, "(1g0)") [(i, i = 1, 20)]
close(fileUnit)

! read 3 rows of data every seven rows

open(newunit = fileUnit, file = "temp.txt", status = "old")

loopOverRows: do

    do i = 1, 3
        read(fileUnit, *, iostat = iostat) Data(i)
        if (is_iostat_end(iostat)) exit loopOverRows ! exit the outer loop if end of file has reached.
    end do
    print *, Data

    do i = 1, 7
        read(fileUnit, *, iostat = iostat)
        if (is_iostat_end(iostat)) exit loopOverRows
    end do

end do loopOverRows

close(fileUnit)

end

Pay attention to how reaching the end of the file can be checked via the intrinsic is_iostat_end() which does not require knowing the number of lines in the file a priori.

Also, note the iso_fortran_env intrinsic module to avoid the use of non-standard, potentially non-portable extensions to the language such as REAL(8). Also, it is good practice not to type modern Fortran syntax in uppercase letters.

Here is the sample output:

   1.00000000000000        2.00000000000000        3.00000000000000     
   11.0000000000000        12.0000000000000        13.0000000000000     

Test it here.

Scientist
  • 1,767
  • 2
  • 12
  • 20