【问题标题】:How can I read the number of lines in Fortran 90 from a text file?如何从文本文件中读取 Fortran 90 中的行数?
【发布时间】:2015-06-07 10:22:31
【问题描述】:

如何读取文本文件中的行数?

我的文本文件似乎是这样的:

1
2
3
.
.
.
n

【问题讨论】:

    标签: fortran


    【解决方案1】:

    用途:

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

    或者:

    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
    

    【讨论】:

    • 您可能需要将io 声明为整数。
    【解决方案2】:

    虽然不清楚,但我认为如果您只需要知道文件中的数字行,只需在命令行上使用wc -l <filename>即可。

    如果您想进一步做任何事情,只需读取字符串中的行数并计数,直到遇到文件末尾。下面是代码:

    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
    

    【讨论】:

    • 使用 Fortran 方法,您甚至不需要实际传输任何内容。
    猜你喜欢
    • 1970-01-01
    • 2018-03-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2014-07-05
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多