C 使用“使用系统”命令时,如何将整数参数传递到脚本文件
当我试图为系统命令提供运行脚本文件的参数时,它不取值,而是取字符串。我可以在注释工作部分时不使用字符串操作吗?或者我可以使用任何其他命令而不是系统命令吗C 使用“使用系统”命令时,如何将整数参数传递到脚本文件,c,C,当我试图为系统命令提供运行脚本文件的参数时,它不取值,而是取字符串。我可以在注释工作部分时不使用字符串操作吗?或者我可以使用任何其他命令而不是系统命令吗 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { unsigned char a = 1; unsigned short b = 100; #if 0
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
unsigned char a = 1;
unsigned short b = 100;
#if 0
char str[30],str1[10];
strcpy(str, "sh shell.sh");//copying to str
strcat(str, " ");
sprintf(str1, "%d", a); //converting int a to string format
strcat(str, str1);
strcat(str, " ");
sprintf(str1, "%d", b);
strcat(str, str1);
system(str); //giving system command for running sh file
#endif
system("sh shell.sh a b");
return 0;
}
Shell.sh
echo -e ("No of arguments :$#")
echo -e ("First argument :$1")
echo -e ("Second argument :$2")
如果不使用字符串参数,就无法真正使用它;这就是底层exec*系统调用所采用的方式,以及int mainint argc、char**argv的工作方式—参数是一个字符串数组 您可以将代码简化为:
snprintf(str, sizeof(str), "sh shell.sh %d %d", a, b);
要在一次操作中完成分布在7行上的操作。您应该严格检查snprintf的结果,尽管str对于问题中的值来说足够长。为什么不在Windows调用中使用单个sprint f或更好的snprintf或sprint f_来格式化整个字符串?关于您的问题,据我所知,您不能将变量直接传递给系统调用,您必须创建一个包含所有内容的字符串,并将其传递给系统函数。