How to read number of lines in Fortran 90 from a text file?

后端 未结 2 1379
无人及你
无人及你 2020-12-03 09:03

How to read number of lines present in a text file.

My text file seems to be like:

1
2
3
.
.
.
n
相关标签:
2条回答
  • 2020-12-03 09:43
    nlines = 0 
    OPEN (1, file = 'file.txt') 
    DO 
        READ (1,*, END=10) 
        nlines = nlines + 1 
    END DO 
    10 CLOSE (1) 
    
    print*, nlines
    
    end
    

    P.S. I totally disagree that this question "seems unclear and shows no effort". Man, you just don't know what you're saying. This question is firstly absolutely clear and secondly it does not have to "show any effort" - that's a stupid requirement in this case, because it is a common practice to ask "how to do A in a language B" - with no efforts required.

    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
    
    0 讨论(0)
  • 2020-12-03 09:43

    Although unclear, but i think, if you just have to know the number lines in the files, just use wc -l <filename> in the command line

    if you want to do anything further, just read the number of lines 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
    

    hope that helps!

    0 讨论(0)
提交回复
热议问题