Search code examples
fortran

Reading missing data from a file


I have to read a file that contains numerical data (mostly reals) but there are also some missing data that are denoted by an asterisk(*). I don't know the positions of the asterisks in advance and I have to find the total valid (numerical) data and the total missing data (asterisks).

I tried doing this with a 'select case' nested in a do loop but failed because

  1. I can't use real type for the selector
  2. I don't think I can put the asterisks in a real matrix

The data file looks something like this

1    0.673070
2    0.750597
3    *
4    0.484100

Any suggestions?


Solution

  • Assuming you know every line has either a real number or an *, I would do something like this:

    Character(len=8) :: LineRead
    Real :: RealNumber
    open(42,file='MyFile.txt')
    
    do (whichever kind of loop you need to control the input)
       read(42,'(a8)') LineRead
       if (LineRead <> '*       ')
         read(LineRead,'(f8.6)') RealNumber
         ! Increment some sort of valid data counter
       end if
    end do
    

    This technique is called reading from an internal file. Any character variable can be 'read' this way.