DSexplorer
DSexplorer

Reputation: 365

How to run FORTRAN program on all the files in a folder?

As of now, I'm opening one file with a .txt extension and running a fortran code on it. However, if I want the program to run on on all the files in a folder with all kinds of extensions. How do I do that?

Upvotes: 3

Views: 3435

Answers (2)

milancurcic
milancurcic

Reputation: 6241

If you are stuck with FORTRAN77, one possible solution is to read the input file name from standard input and open that file accordingly:

character(len=9999) inputFile

read(unit=5,fmt=*)inputFile
open(unit=21,file=trim(inputFile))

Then, execute your program on all files through a shell script loop:

for file in *;do
    echo $file | myFortranProgram
done

If you have a more modern compiler, you can use a Fortran 2003 feature GET_COMMAND_ARGUMENT:

character(len=9999) :: inputFile 

call GET_COMMAND_ARGUMENT(1,VALUE=inputFile)
open(unit=21,file=trim(inputFile))

Then execute your program through a loop as described above:

for file in *;do
    ./myFortranProgram $file
done   

Remember that when looping over files, you are responsible for making sure that your Fortran program will work with those files and that it is able to handle exceptions, e.g. directories or some other file extensions, or loop over specific files from shell accordingly.

Upvotes: 4

M. S. B.
M. S. B.

Reputation: 29401

I usually create a file with a list of the files that I want to process, e.g., using the ls or find commands on a Unix OS. This also allows one to modify the list with an editor. Then I design the Fortran program to read the filenames from that file, then open, process and close those files in succession.

If you can predict possible filenames based on a pattern, you can test whether a file of a particular name exists using the INQUIRE statement. This could be used to loop through all possible filenames. This may or may not be practical depending on how many possible files there are.

Upvotes: 2

Related Questions