fortranfortran90fortran77fortran95

How to read a special line in .txt file using Fortran?


I have a .txt file, which has next special lines:

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

I want to read numbers after comment line !INPUT_PARAMETERS. So, if i have:

integer:: A,B,C,D

I want to receive that A=1,B=2,C=5,D=10. How can i achieve that?


Solution

  • I've got a snippet of code I use which might be useful,

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

    where this is called as follows,

    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