It is a commont task that you have to read some information from a file to perform some calculations. This uses to be done inside a loop. The problem is that many times you don't know how many lines the file has, so you can't use a counter as the condition to stop reading. Or maybe you know, but you don't want to pass that information to the program every time you run it. In this post I'm showing how to "teach" a Fortran and Bash program to read until it reach the end of the file.
Fortran version
In fortran, you have to use the option iostat when you use the read function. By doing so, there is an integer variable (ierr in the example below) that contains the output code of the last read action. If it is different to 0, it means that the end of the files has been reached (or something even worse). I think the example is self explanatory
program readtotheendimplicit none
integer :: i, ierr, number
open(unit=10,file='filein.asc',status='old',action='read')
ierr=0i=0do while(ierr.eq.0)i=i+1read(10,*,iostat=ierr),numberprint*, 'Element', i, numberenddoclose(unit=10)
print*, 'Reading finished', i-1, 'lines'
end program
Bash version
The Bash version of this idea is to use a while loop and feed it with the input file
set -ex
while read number; do
# Here you can do whatever you want to do with the variable, which is stored in the variable number
done < filein.asc
This is a really elegant solution to perform some operation to all the lines of a file.
2 Comments:
doesn't for example
c------------------
open(10,file=input1,form='unformatted')
100 read(10,end=999)ia
goto 100
999 continue
c------------------
serve for the same purpose, or am I wrong?
thanks anyway :)
Of course, that's yet another way to proceed :) Nevertheless it's in general not considered a good idea to use the "goto" command. It is an old fashioned way of programming fortran xD
Post a Comment