Reading a character string of unknown length

后端 未结 4 2150
轻奢々
轻奢々 2021-02-02 00:07

I have been tasked with writing a Fortran 95 program that will read character input from a file, and then (to start with) simply spit it back out again. The tricky part is that

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 00:39

    Here's a function for Fortran 2003, which sets an allocatable string (InLine) of exactly the length of the input string (optionally trimmed), or returns .false. if end of file

    function ReadLine(aunit, InLine, trimmed) result(OK)
    integer, intent(IN) :: aunit
    character(LEN=:), allocatable, optional :: InLine
    logical, intent(in), optional :: trimmed
    integer, parameter :: line_buf_len= 1024*4
    character(LEN=line_buf_len) :: InS
    logical :: OK, set
    integer status, size
    
    OK = .false.
    set = .true.
    do
        read (aunit,'(a)',advance='NO',iostat=status, size=size) InS
        OK = .not. IS_IOSTAT_END(status)
        if (.not. OK) return
        if (present(InLine)) then
            if (set) then
                InLine = InS(1:size)
                set=.false.
            else
                InLine = InLine // InS(1:size)
            end if
        end if
        if (IS_IOSTAT_EOR(status)) exit
    end do
    if (present(trimmed) .and. present(InLine)) then
        if (trimmed) InLine = trim(adjustl(InLine))
    end if
    
    end function ReadLine
    

    For example to do something with all lines in a file with unit "aunit" do

     character(LEN=:), allocatable :: InLine
    
     do while (ReadLine(aunit, InLine))
       [.. something with InLine]
     end do
    

提交回复
热议问题