Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Fortran read from file problems

  1. Jan 3, 2012 #1
    I've been given a data file laid out as such:

    heading1 heading2 heading3
    x1 y1 z1
    x2 y2 z2
    x3 y3 z3

    where x=integer, y,z=real

    I need to count the number of lines to allocate x, y and z their sizes. My first attempt looked like:


    OPEN(21, FILE='data.dat', STATUS=OLD)


    DO WHILE (.NOT. ok)
    READ(21,'\,1X,I1') first
    IF (first .EQ. ' ') THEN



    END IF

    END DO


    This runs into the problem that i don't know what type to make "first" as it'll be looking at integers until the last line.

    If anyone can help it'd be much appreciated!
  2. jcsd
  3. Jan 3, 2012 #2


    User Avatar

    Staff: Mentor

    Read the data as character data, then it will accept anything.

    Also, the simplest way to detect the end of file is to specify an "iostat variable" to receive the status of the read statement. After the read statement, if the iostat variable is 0, the read was OK; if it's -1, you reached the end of file; otherwise there was some kind of input error.

    Something like this (untested because I don't have a Fortran compiler handy):

    Code (Text):

          integer status, counter
          character*1 dummy

          status = 0
          counter = 0
          do while (status .eq. 0)
              read (21, '(1x, a1)', iostat=status) dummy
              if (status .eq. 0)
                  counter = counter + 1
              end if
          end do

          if (status .eq. -1) then
              print *, 'The file has ', counter, ' lines.'
              print *, 'There was an input error!  Status code = ', status
          end if
  4. Jan 5, 2012 #3
    That code worked like a charm, thanks!
  5. Jan 12, 2012 #4
    Re: The plot thickens....

    As the title suggests, theres more I'd like to ask:

    I want to allow users to input a file name for the program to open:

    CHARACTER*40 filename


    Somehow this doesn't work, it just says the file doesn't exist. Any thoughts?
  6. Jan 12, 2012 #5


    User Avatar

    Staff: Mentor

    The program may be looking for the file in a different directory (folder) than you're expecting. Have you tried using a full pathname?

    Also, this may depend on the operating system, so it might be useful to tell us which OS you're using.
  7. Jan 12, 2012 #6
    After talking with some friends at uni we realised that it's just the IDE I was using that was the problem. (Silverfrost plato)

    After using the universities software it works fine.

    Thanks for the speedy response once again!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook