简体   繁体   中英

How to send command to Linux command from C program

I am trying to send a command to a Linux command line from a C program and there is one part I am not sure how to do.

For example in my C code I have

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

What I would like to be able to do is add a number to the end of "image" and increment it every time the program runs, but how can I pass in a variable n to the system() function that is only looking for a const char ?

I tried this but it did not work:

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

I've tried searching on this and haven't found anything about how to add a variable to it. Sorry for the noob question.

char fileName[80];

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

First, a String is a char array, so declare (I think you know, just to emphasize):

char command[32]; 

So, simple solution will be:

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

Then call system(command); . This is just what you need.


EDIT:

If you need program output , try 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);

Sources: C: Run a System Command and Get Output?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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