Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute command line and return command output

Currently, I am using shell command line calls from my fortran program using non-standard SYSTEM intrinsic routine (similar to Fortran 2008 EXECUTE_COMMAND_LINE intrinsic):

CALL SYSTEM(commandStr)

where commandStr is a character string containing the shell command I want to execute. At the moment, I am not aware of a direct way to return the output of commandStr, but only its return status. So, what I am doing now is writing output into a file, and then reading the file from within the Fortran program. Example:

CALL SYSTEM('sed ''s/,//g'' myFile > dummyFile')

if I want to remove commas from myFile. I then use OPEN and READ to get contents of dummyFile.

This works just fine, however I am concerned about writing/reading files from disk, especially if I was doing this within a long loop, and if commandStr output was big. Is there a way to re-direct commandStr output into a memory buffer (not hard disk) which I could access from my Fortran program directly (maybe through a specific UNIT number)?

like image 765
milancurcic Avatar asked Oct 20 '11 16:10

milancurcic


People also ask

How do I execute a command and get the output of the command within C++ using Posix?

How to execute a command and get the output of command within C++ using POSIX? You can use the popen and pclose functions to pipe to and from processes. The popen() function opens a process by creating a pipe, forking, and invoking the shell.

How do I copy the output of a command to a file?

Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.


1 Answers

If this is in a POSIX environment, the library function popen() might also be available.

iunit = popen ('sed ''s/,//g'' myFile', 'r')

Look at the documentation for your Fortran environment since I'm not sure of the semantics for connecting the i/o to Fortran. If it is like the C runtime library, the file connection also needs a special function to close it, pclose().

like image 130
wallyk Avatar answered Sep 21 '22 03:09

wallyk