【问题标题】:How to read a special line in .txt file using Fortran?如何使用 Fortran 读取 .txt 文件中的特殊行?
【发布时间】:2020-11-18 00:55:05
【问题描述】:

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

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

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

integer:: A,B,C,D

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

【问题讨论】:

  • 您似乎想使用 NAMELIST。否则,您需要编写一个解析器,将每一行读入一个字符串。当前读取的字符串用于确定如何处理下一行。
  • @evets 建议更容易:移动到文件中下一行包含感兴趣数字的位置,然后read(unit, *) a, b, c, d 应该可以解决问题。至于如何移动到正确的位置,现在是时候让您与我们分享您目前拥有的代码,以便我们了解您需要/想要多少帮助。
  • 找到正确的位置是我评论的重点,@HighPerformanceMark。假设!INPUT PARAMETERS 在文件中并且紧接在所需数据之前,则只需在read(unit,'(A)') string 后跟if (trim(string) == '!INPUT PARAMETERS') then。维奥拉,你找对地方了。问题,当然,以及为什么需要解析读取的字符串,大概是文件中的其他行很重要。

标签: fortran fortran90 fortran77 fortran95


【解决方案1】:

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

!---------------------------------------------------
! 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2015-01-28
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多