簡體   English   中英

如何從C程序向Linux命令發送命令

[英]How to send command to Linux command from C program

我正在嘗試從C程序向Linux命令行發送命令,但我不確定其中一部分是怎么做的。

例如在我的C代碼中

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

我想做的是在“圖像”的末尾添加一個數字,並在每次程序運行時將其遞增,但是我如何將變量n傳遞給僅尋找一個變量的system()函數呢? const char

我試過了,但是沒有用:

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

我已經嘗試過搜索,但是還沒有找到有關如何向其中添加變量的任何信息。 對不起,菜鳥問題。

char fileName[80];

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

首先,一個String是一個char數組,所以要聲明(我想你只是想強調一下):

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:運行系統命令並獲取輸出?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM