Pavol Namer
Pavol Namer

Reputation: 85

How to add a shell command and use the result in a Fortran program?

Is it possible to call shell command from a Fortran script?

My problem is that I analyze really big files. These files have a lot of lines, e.g. 84084002 or similar. I need to know how many lines the file has, before I start the analysis, therefore I usually used shell command: wc -l "filename", and than used this number as a parameter of one variable in my script.

But I would like to call this command from my program and use the number of lines and store it into the variable value.

Upvotes: 5

Views: 9527

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 208043

You should be able to do something like this:

command='wc -l < file.txt > wc.txt' 
CALL system(command) 
OPEN(unit=nn,file='wc.txt') 
READ(nn,*) count 

Upvotes: 4

Pinaki Saha
Pinaki Saha

Reputation: 1

You can output the number of lines to a file (fort.1)

 wc -l file|awk '{print $1}' > fort.1

In your Fortran program, you can then store the number of lines to a variable (e.g. count) by reading the file fort.1:

read (1,*) count

then you can loop over the variable count and read your whole file

do 1,count 
read (file,*) 

Upvotes: 0

High Performance Mark
High Performance Mark

Reputation: 78364

Since 1984, actually in the 2008 standard but already implemented by most of the commonly-encountered Fortran compilers including gfortran, there is a standard intrinsic subroutine execute_command_line which does, approximately, what the widely-implemented but non-standard subroutine system does. As @MarkSetchell has (almost) written, you could try

CALL execute_command_line('wc -l < file.txt > wc.txt' ) 
OPEN(unit=nn,file='wc.txt') 
READ(nn,*) count 

What Fortran doesn't have is a standard way in which to get the number of lines in a file without recourse to the kind of operating-system-dependent workaround above. Other, that is, than opening the file, counting the number of lines, and then rewinding to the start of the file to commence reading.

Upvotes: 6

Related Questions