2017-06-21 87 views
-1

我想从C程序向Linux命令行发送命令,并且有一部分我不知道该怎么做。如何从C程序向Linux命令发送命令

举例来说,在我的C代码,我有

system("raspistill -o image.jpg"); 

我想做什么就能做的就是添加一个数字的“形象”结束,每个程序运行时间增加了,但如何我可以传递一个变量nsystem()函数只能查找const char

我试过,但没有奏效:

char fileName = ("raspistill -o image%d.jpg",n); 
system(filename); 

我试过这个搜索,并没有发现有关如何将变量添加到任何东西。对于noob问题抱歉。

+2

使用'sprintf'构建**字符串**,然后将其传递给'system'。 –

+3

[c string和int concatenation]可能重复(https://stackoverflow.com/questions/5172107/c-string-and-int-concatenation) –

回答

2
char fileName[80]; 

sprintf(fileName, "raspistill -o image%d.jpg",n); 
system(filename); 
+0

谢谢!这工作完美!我没有意识到sprintf()可以这样使用。 – Nate

0

首先,一个字符串是一个字符数组,所以声明(我想你知道,只是强调):

char command[32]; 

所以,简单的解决方案将是:

sprintf(command, "raspistill -o image%d.jpg", n); 

然后致电system(command);。这正是你需要的。


编辑:

如果您需要程序输出,尝试popen

char command[32]; 
char data[1024]; 
sprintf(command, "raspistill -o image%d.jpg", n); 
//Open the process with given 'command' for reading 
FILE* file = popen(command, "r"); 
// do something with program output. 
while (fgets(data, sizeof(data)-1, file) != NULL) { 
    printf("%s", data); 
} 
pclose(file); 

来源:C: Run a System Command and Get Output?

http://man7.org/linux/man-pages/man3/popen.3.html