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

  • Topic: Fortran 
  • Thread starter Thread starter SAMANDEEP
  • Start date Start date
  • Tags Tags
    Data files Fortran
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
2 replies · 3K views
SAMANDEEP
Messages
1
Reaction score
0
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.
 
Physics news on Phys.org
Is there some sort of marker to tell the code that the end of file has been reached?
 
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:
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:
do
    read (4, *, iostat=io) x
    if (io /= 0) exit
    sum = sum + x
end do
 
Last edited: