首页 > 解决方案 > 如何使用 Fortran 读取 .txt 文件中的特殊行?

问题描述

我有一个 .txt 文件,其中包含以下特殊行:

....
....
!INPUT_PARAMETERS
1 2 5 10
...
...

我想在注释行!INPUT_PARAMETERS 之后阅读数字。所以,如果我有:

integer:: A,B,C,D

我想收到 A=1,B=2,C=5,D=10。我怎样才能做到这一点?

标签: fortranfortran90fortran77fortran95

解决方案


我有一段可能有用的代码,

!---------------------------------------------------
! Locate file in input

subroutine locate(fileid, keyword, have_data)
    implicit none
    
    integer,intent(in)          :: fileid               ! File unit number
    character(len=*),intent(in) :: keyword              ! Input keyword 
    logical,intent(out)         :: have_data            ! Flag: input found

    character*(100)             :: linestring           ! First 100 chars
    integer                     :: keyword_length       ! Length of keyword
    integer                     :: io                   ! File status flag

    keyword_length = len(keyword)
    rewind(fileid)
    
    ! Loop until end of file or keyword found
    do
        ! Read first 100 characters of line
        read (fileid,'(a)',iostat=io) linestring

        ! If end of file is reached, exit
        if (io.ne.0) then 
            have_data = .false.
            exit
        end if
        
        ! If the first characters match keyword, exit
        if (linestring(1:keyword_length).eq.keyword) then
            have_data = .true.
            exit
        endif

    end do

end subroutine locate

这被称为如下,

call locate(infileid, '!INPUT_PARAMETERS', found)
if (found) then
    !You can do error checking with readin flag
    read(infileid,*, IOSTAT=readin) a, b, c, d
else
    !Set default values
    a = 0;  b = 0
    c = 0;  d = 0
endif

推荐阅读