Lip*_*pis 20 c++ linux command-line
我只是想知道哪种是在C++中执行外部命令的最佳方法,如果有的话我如何获取输出?
编辑:我猜我必须告诉我这个世界上我是新手,所以我想我需要一个有效的例子.例如,我想执行如下命令:
ls -la
Run Code Online (Sandbox Code Playgroud)
我怎么做?
Meh*_*ari 23
使用该popen
功能.
示例(不完整,生产质量代码,无错误处理):
FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);
Run Code Online (Sandbox Code Playgroud)
小智 20
一个例子:
#include <stdio.h>
int main() {
FILE * f = popen( "ls -al", "r" );
if ( f == 0 ) {
fprintf( stderr, "Could not execute\n" );
return 1;
}
const int BUFSIZE = 1000;
char buf[ BUFSIZE ];
while( fgets( buf, BUFSIZE, f ) ) {
fprintf( stdout, "%s", buf );
}
pclose( f );
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*acs 16
popen
绝对是你正在寻找的工作,但它有一些缺点:
如果要调用子进程并提供输入和捕获输出,那么您必须执行以下操作:
int Input[2], Output[2];
pipe( Input );
pipe( Output );
if( fork() )
{
// We're in the parent here.
// Close the reading end of the input pipe.
close( Input[ 0 ] );
// Close the writing end of the output pipe
close( Output[ 1 ] );
// Here we can interact with the subprocess. Write to the subprocesses stdin via Input[ 1 ], and read from the subprocesses stdout via Output[ 0 ].
...
}
else
{ // We're in the child here.
close( Input[ 1 ] );
dup2( Input[ 0 ], STDIN_FILENO );
close( Output[ 0 ] );
dup2( Output[ 1 ], STDOUT_FILENO );
execlp( "ls", "-la", NULL );
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以根据需要替换execlp
任何其他exec函数.