C:运行系统命令并获取输出? [英] C: Run a System Command and Get Output?
本文介绍了C:运行系统命令并获取输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何运行外部从 C 编写程序并解析其输出?
我想在 linux 中运行一个命令并获得它输出的返回文本,但我不希望将此文本打印到屏幕上.有没有比制作临时文件更优雅的方法?
I want to run a command in linux and get the text returned of what it outputs, but I do not want this text printed to screen. Is there a more elegant way than making a temporary file?
推荐答案
您想要popen" 函数.这是运行命令ls/etc"并输出到控制台的示例.
You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command
" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
这篇关于C:运行系统命令并获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文