I want to send an integer as a parameter to the system()
function in C, but I haven't been able to.
I'd like to do this because I have some jpg files which are regularly named as 1.jpg , 2.jpg ... 17.jpg ... ect.
The program would assign a randomly chosen value to an integer variable, and open the image file with the same name as the randomly chosen integer by using the system()
function.
What I envision:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
i=rand()%30+1; // for example i=17
system("eog %d.jpg &",i); //and i want to open 17.jpg here with eog
}
I know there are too many arguments to the system()
function above; I just wanted to give an example of what I wanted.
Is there a way to do this, and if not, how else could I go about doing what I described above?
You need to convert the integer into a string argument:
int runSystem(const char *fmt, ...)
{
char buffer[4096];
va_list va;
va_start(va, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, va);
va_end(va);
return system(buffer);
}
main()
{
srand(time(NULL));
i=1+rand()%30; // for example i=17
runSystem("eog %d.jpg &",i); //and i want to open 17.jpg here with eog
}