0

C 中有没有办法将整个命令行选项和参数存储在单个字符串中。我的意思是如果我的命令行是./a.out -n 67 89 78 -i 9那么一个字符串str应该能够打印整个命令行。现在,我能做的是以不同的向量形式打印值。

#include <stdio.h>
#include <getopt.h>
#include <string.h>


int main(int argc, char* argv[]) {
 int opt;

for(i=0;i<argc;i++){
printf("whole argv was %s\n", argv[i]);
}

while((opt = getopt(argc, argv, "n:i")) != -1) {
switch (opt){
    case 'n':
             printf("i was %s\n", optarg);
             break;

    case 'i':
             printf("i was %s\n", optarg);
             break;
      }
   }
  return 0;
 }

我想要这个,因为optarg只打印我的第一个参数并且我希望打印所有参数,所以我想在将它存储在字符串中之后对其进行解析。

4

3 回答 3

2

您可以做的是遍历 argv 并使用strcat

char* CommandLine = 0;
unsigned int CommandLineLength = 0;
unsigned int i = 0;

for (i = 0; i < argc; i++) {
    CommandLineLength += strlen(argv[i]) + 3; // Add one extra space and 2 quotes
}

CommandLine = (char*) malloc(CommandLineLength + 1);
*CommandLine = '\0';

// Todo: Check if allocation was successfull...

for (i = 0; i < argc; i++) {
    int HasSpace = strchr(argv[i], ' ') != NULL;
    if (HasSpace) {
        strcat(CommandLine, "\"");
    }
    strcat(CommandLine, argv[i]);
    if (HasSpace) {
        strcat(CommandLine, "\"");
    }
    strcat(CommandLine, " ");
}
// Do something with CommandLine ...
free(CommandLine);
于 2013-08-15T14:58:57.943 回答
0

这取决于平台。

在 Windows 中,您可以使用GetCommandLine().

于 2013-08-15T15:14:57.673 回答
-1

简单地写一个这样的函数:

char * combineargv(int argc, char * * argv)
{
    int totalsize = 0;
    for (int i = 0; i < argc; i++)
    {
       totalsize += strlen(argv[i]);
    }
    // Provides space for ' ' after each argument and a '\0' terminator.
    char *ret = malloc(totalsize + argc + 1);
    if (NULL == ret)
    {
        // Memory allocation error.
    }
    for (int i = 0; i < argc; i++)
    {
        strcat(ret, argv[i]);
        strcat(ret, " ");
    }
    return ret;
}

这将简单地组合所有这些,在 args 之间放置空格

更新:我已经修改了原始文件以消除缓冲区溢出问题。

于 2013-08-15T15:08:28.730 回答