How to handle blank in formatted integer input

460 Views Asked by At

I have a file like this

1980  01  23 

1982  04  30
1983  05  22
1984        
1985  02  11

I tried to read data using format "(3I4)"

implicit none

integer, parameter :: FUnitIn = 10
character(len=255) :: FNameIn = "./test.txt"


integer :: FStatOpen, FStatRead
integer :: yyyy, mm, dd


open ( unit    = FUnitIn, &
       file    = trim(FNameIn), &
       access  = "sequential", &
       form    = "formatted", &
       status  = "old", &
       iostat  = FStatOpen)
if (FStatOpen /= 0) then ! ERROR
    stop
end if


do
    read (FUnitIn, "(3I4)", iostat=FStatRead) yyyy, mm, dd
    if (FStatRead /= 0) then
        exit
    else
        write (6, "(3I4)") yyyy, mm, dd
    end if
end do

I got three zeros for the blank line. Are there any options to handle blank input?

1

There are 1 best solutions below

0
Scientist On

You can read each line in a character variable, and check its adjusted-trimmed length if your sole goal is to skip the empty line, something like the following code (see variable record). Going beyond this simple implementation requires some extra information from you as to what behavior exactly you want to get.

implicit none

integer, parameter  :: FUnitIn = 10
character(len=255)  :: FNameIn = "./test.txt"


integer             :: FStatOpen, FStatRead
integer             :: yyyy, mm, dd
character(len=1023) :: record


open ( unit    = FUnitIn, &
    file    = trim(FNameIn), &
    access  = "sequential", &
    form    = "formatted", &
    status  = "old", &
    iostat  = FStatOpen)
if (FStatOpen /= 0) then ! ERROR
    stop
end if


do
    read (FUnitIn, "(3I4)", iostat=FStatRead) record
    if (FStatRead /= 0) then
        exit
    elseif ( len_trim(adjustl(record)) > 0 ) then
        read (record, *) yyyy, mm, dd            
        write (6, "(3I4)") yyyy, mm, dd
    end if
end do