You are on page 1of 2

24 - Counting number of lines in a file within FORTRAN code

If you want to determine the number of line in a given file within your FORTRAN code,
you can do this following nice trick!
program count_lines
implicit none
integer:: n
character(len=60):: cmd
cmd = "cat file_name.dat | grep '[^ ]' | wc -l > nlines.txt"
call system(cmd)
open(1,file='nlines.txt')
read(1,*) n
print*, "Number of lines are", n
cmd = 'rm nlines.txt'
call system(cmd)
end program
Thissimplecode,useslinuxcommandtofindthenumberoflines.
Noticethatcat file_name.dat | grep '[^ ]' | wc -l returnsthenumberoflinesina
filewithignotingtheblanklines.

26 - How to check an exisiting file in FORTRAN


The inquire command in FORTRAN will help us to see what is on disk, and what is currently
attached to units in our code.
For checking whether a file is existing in the current directory (where our fortran code is there) or
not
we need to use

inquire(file='file_name', exist=lexist)
where lexist is a logical variable. if it is .true. then the file is exisiting in the current directory!
We can also check whether a file has been opened in the code or not.

inquire(unit=11, opened=lopen)
or

inquire(file='file_name', opened=lopen)
if the file has been already opened, the logical variable lopen is .true. otherwise it is .false. .
Posted by Amin at No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Object 1

Labels: Fortran

Monday, March 25, 2013


25 - generating random number in FORTRAN
In Fortran one can use
real:: rnd
call random_number(rnd)
to generate random numbers between [0,1]. But the problem is that if we reuses this peice of the
code again, we will get exactly the same squence of random numbers. To produce a different
sequece random number each time, the generator can be seede in a number of ways such as:
integer:: count, seed
real:: rnd
call system_clock(count)
seed=count
call random_seed(put=seed)
call random_number(rnd)

You might also like