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:


    open(unit=1,file='mu.dat',status='old')

    open(unit=2,file='md.dat',status='old')

    open(unit=3,file='ms.dat',status='old')

    do i=1,386,1
    read(1,*)mu(i)
    read(2,*)md(i)

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

    Thanks,
    Saman.
     
  2. jcsd
  3. Jul 24, 2013 #2

    mathman

    User Avatar
    Science Advisor
    Gold Member

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

    jtbell

    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.

    http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/iostatus.html

    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.'
    else
        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):

    do
        read (4, *, iostat=io) x
        if (io /= 0) exit
        sum = sum + x
    end do
     
     
    Last edited: Jul 25, 2013
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: How to read data from various files of different sizes in fortran
Loading...