有没有办法限制命令行参数的数量?
Is there a way to limit the number of command line arguments?
我正在尝试在 C 中执行命令 'echo'。
我希望在命令行中将命令 'echo' 后的整个句子读入 argv[1],而不是将每个单词作为单独的参数传递。
在 C 中可以吗?
您可以使用 argc
遍历 argv
的每个元素,以确保您不会读得太深。
您也可以要求程序的启动是:./myProgram "Here is my nice sentence"
您不能直接执行此操作,因为 shell 甚至在您的程序启动之前就已拆分参数。
也许你想要这样的东西:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char sentence[500] = { 0 };
for (int i = 1; i < argc; i++)
{
strcat(sentence, argv[i]);
if (i < argc - 1)
strcat(sentence, " ");
}
printf("sentence = \"%s\"", sentence);
}
免责声明:为简洁起见,未进行边界检查。
调用示例:
> myecho Hello World 1 2 3
sentence = "Hello World 1 2 3"
我正在尝试在 C 中执行命令 'echo'。
我希望在命令行中将命令 'echo' 后的整个句子读入 argv[1],而不是将每个单词作为单独的参数传递。
在 C 中可以吗?
您可以使用 argc
遍历 argv
的每个元素,以确保您不会读得太深。
您也可以要求程序的启动是:./myProgram "Here is my nice sentence"
您不能直接执行此操作,因为 shell 甚至在您的程序启动之前就已拆分参数。
也许你想要这样的东西:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char sentence[500] = { 0 };
for (int i = 1; i < argc; i++)
{
strcat(sentence, argv[i]);
if (i < argc - 1)
strcat(sentence, " ");
}
printf("sentence = \"%s\"", sentence);
}
免责声明:为简洁起见,未进行边界检查。
调用示例:
> myecho Hello World 1 2 3
sentence = "Hello World 1 2 3"