parsingfile-iofortran

How to find and extract a numeric value from a text file?


I have a file called "RFEM_Information.txt" which has 13 lines.

[None]======================================================================
        <Drainage>DrainedUndrained</Drainage>
        <Scr>0</Scr>
        <UseCavitationCutOff>No</UseCavitationCutOff>
        <pt>100</pt>
        <E>30</E>
        <Nu>0.25</Nu>
        <K>20</K>
[None]======================================================================
[Log][None]No OF NODES     = 474
[Log][None]
[Log][None]BEST STSR = 1.528
[Log] [None]=================================================================

I want to find line 12 (in general the line number is unknown) which has "[Log][None]BEST STSR = 1.528" and I want to extract the number or all the information of the line after "=" (I want to return as a number 1.528).

How can I find the relevant line and read the value from it?


Solution

  • Try using Fortran index function to scan the line for "BEST STSR" substring, then extract the number.

    Here is an example:

    program main
        implicit none
        character(128) :: line
        integer :: i, stat, unit
        real :: val
        
        open (FILE="data.txt", NEWUNIT=unit, STATUS="old", ACTION="read", IOSTAT=stat)
        if (stat /= 0) error stop "Cannot open file"
          
        do while (.true.)
            read (unit, "(a)", IOSTAT=stat) line
            if (stat /= 0) exit
    
            ! Scan buffer for keyword "BEST STSR". Extract number if keyword is found.
            i = index(line, "BEST STSR")
            if (i /= 0) then
                ! length("BEST STSR =") = 11
                read (line(i+11:), *, IOSTAT=stat) val
                if (stat /= 0) error stop "Cannot read value"
    
            end if
        end do
          
        close (unit)
        
    end program main