Trix & Graphix

Reading a file until it ends

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 readtotheend
implicit none
integer :: i, ierr, number
open(unit=10,file='filein.asc',status='old',action='read')
ierr=0
i=0
do while(ierr.eq.0)
i=i+1
read(10,*,iostat=ierr),number
print*, 'Element', i, number
enddo
close(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.