8

How can I read the number of lines present in a text file?

My text file seems to be like:

1
2
3
.
.
.
n
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adi
  • 137
  • 1
  • 1
  • 2

2 Answers2

23

Use:

nlines = 0
OPEN (1, file = 'file.txt')
DO
    READ (1,*, END=10)
    nlines = nlines + 1
END DO
10 CLOSE (1)

print*, nlines

end

Or:

nlines = 0
OPEN (1, file = 'file.txt')
DO
  READ(1,*,iostat=io)
  IF (io/=0) EXIT
  nlines = nlines + 1
END DO
CLOSE (1)

print*, nlines
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prograils
  • 2,248
  • 1
  • 28
  • 45
2

Although it is unclear, I think if you just have to know the number lines in the files, just use wc -l <filename> on the command line.

If you want to do anything further, just read the number of lines in a character string and count until the end of file is encountered. Here is the code below:

character :: inputline*200

OPEN(lin, file=inputfile, status='old', action='read', position='rewind')

loop1: DO
   READ(lin,*,iostat=eastat) inputline
   IF (eastat < 0) THEN
    numvalues = numvalues + 1
WRITE(*,*) trim(inputfile), ' :number of records =', numvalues-1
EXIT loop1

ELSE IF (eastat > 0) THEN
    STOP 'IO-error'
ENDIF
    numvalues = numvalues + 1

END DO loop1
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PT2009
  • 117
  • 1
  • 10