user227666
user227666

Reputation: 774

Command line argument to string in C

Is there a way in C to store the whole command line options and arguments in a single string. I mean if my command line is ./a.out -n 67 89 78 -i 9 then a string str should be able to print the whole command line. Now, what I am able to do is to print values in different vector forms.

#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;
 }

I want this, as optarg only is printing my first argument and I want all the arguments to be printed, so I want to parse it after storing it in string.

Upvotes: 0

Views: 2089

Answers (3)

bkausbk
bkausbk

Reputation: 2790

What you can do is to loop over argv and build a string with 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);

Upvotes: 2

phyrrus9
phyrrus9

Reputation: 1467

Simply write a function like this:

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;
}

This will simply combine all of them, placing spaces between args

Update: I have modified the original to eliminate the buffer overflow issue.

Upvotes: -1

Jonathan Wood
Jonathan Wood

Reputation: 67195

It depends on the platform.

In Windows, you can use GetCommandLine().

Upvotes: 0

Related Questions