-1

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.

Gillespie
  • 5,780
  • 3
  • 32
  • 54
Nate
  • 37
  • 1
  • 4

2 Answers2

2
char fileName[80];

sprintf(fileName, "raspistill -o image%d.jpg",n);
system(filename);
Ivan Sheihets
  • 802
  • 8
  • 17
0

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

leosf6308
  • 109
  • 6