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

How to read data from various files of different sizes in fortran

  1. Jul 24, 2013 #1
    In my Fortran program, I want to read data from various files whose size I do not know in prior. The input files which I am trying to read may contain different number of entries. If I have same and known number of entries in all files (say 386), I can use something like:




    do i=1,386,1

    Can someone please help me in doing it if I don't know the number of rows in my data files in prior???

  2. jcsd
  3. Jul 24, 2013 #2


    User Avatar
    Science Advisor

    Is there some sort of marker to tell the code that the end of file has been reached?
  4. Jul 24, 2013 #3


    User Avatar

    Staff: Mentor

    Use an IOSTAT clause in your READ statement to store the read status (which indicates when you have reached the end of file) into a variable; then test that variable to decide whether to exit your input-loop.


    Just as a matter of personal taste, I think the if-statement nested inside the do-loop is a bit clunky, in the examples on that page. Here's how I'd do the second example (reading from a file on unit 4, instead of from *):

    Code (Text):

    open (unit=4, file='mydata.dat', status='old')
    sum = 0

    read (4, *, iostat=io) x
    do while (io == 0)
        sum = sum + x
        read (4, *, iostat=io) x
    end do

    if (io > 0) then
        write (*, *) 'Check your data file.  Something was wrong.'
        write (*, *) 'The total is ', sum
    end if
    Or you can use an EXIT to get out of the loop, then you need only one READ statement:

    Code (Text):

        read (4, *, iostat=io) x
        if (io /= 0) exit
        sum = sum + x
    end do
    Last edited: Jul 25, 2013
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook