简体   繁体   English

执行命令行并返回命令输出

[英]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): 目前,我正在使用来自我的fortran程序的shell命令行调用,使用非标准的SYSTEM内部例程(类似于Fortran 2008 EXECUTE_COMMAND_LINE内部函数):

CALL SYSTEM(commandStr)

where commandStr is a character string containing the shell command I want to execute. 其中commandStr是一个包含我想要执行的shell命令的字符串。 At the moment, I am not aware of a direct way to return the output of commandStr, but only its return status. 目前,我不知道返回commandStr输出的直接方法,只知道返回状态。 So, what I am doing now is writing output into a file, and then reading the file from within the Fortran program. 所以,我现在正在做的是将输出写入文件,然后从Fortran程序中读取文件。 Example: 例:

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

if I want to remove commas from myFile. 如果我想从myFile中删除逗号。 I then use OPEN and READ to get contents of dummyFile. 然后我使用OPEN和READ来获取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. 这很好用,但是我担心从磁盘写入/读取文件,特别是如果我在长循环中这样做,并且如果commandStr输出很大。 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)? 有没有办法将commandStr输出重定向到我可以直接从我的Fortran程序访问的内存缓冲区(而不是硬盘)(可能通过特定的UNIT号码)?

If this is in a POSIX environment, the library function popen() might also be available. 如果这是在POSIX环境中,库函数popen()也可能是可用的。

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. 查看Fortran环境的文档,因为我不确定将i / o连接到Fortran的语义。 If it is like the C runtime library, the file connection also needs a special function to close it, pclose() . 如果它像C运行时库,文件连接也需要一个特殊的函数来关闭它, pclose()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM