我想将一个整数作为参数发送到 C 中的 system()
函数,但我无法做到。
我想这样做是因为我有一些 jpg 文件,这些文件通常命名为 1.jpg 、 2.jpg ... 17.jpg ... 等等。
程序会分配将随机选择的值赋给一个整数变量,并使用 system()
函数打开与随机选择的整数同名的图像文件。
我的设想:
#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
}
我知道上面的 system()
函数有太多参数;我只是想举一个我想要的例子。
有没有办法做到这一点,如果没有,我还能怎样做我上面描述的事情?
最佳答案
使用 snprintf
构建您的字符串并将其传递给 system
。
char cmd[LEN];
snprintf(cmd, sizeof(cmd), "eog %d.jpg &", i);
system(cmd);
关于c - system() 函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10105644/