6

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But it doesn't support bash like syntax like [ -f test.txt ] && echo 'test.text file available', shows junky message with exitcode as nonzero
4

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 

1 Comment

The system command is not standard fortran and should be avoided. Some compilers do not have it, others use sh. It is advised to use EXECUTE_COMMAND_LINE.
0

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,*) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.