Parse string into argv/argc

前端 未结 13 899
生来不讨喜
生来不讨喜 2020-11-28 07:45

Is there a way in C to parse a piece of text and obtain values for argv and argc, as if the text had been passed to an application on the command line?

This doesn\'

13条回答
  •  佛祖请我去吃肉
    2020-11-28 08:02

    I ended up writing a function to do this myself, I don't think its very good but it works for my purposes - feel free to suggest improvements for anyone else who needs this in the future:

    void parseCommandLine(char* cmdLineTxt, char*** argv, int* argc){
        int count = 1;
    
        char *cmdLineCopy = strdupa(cmdLineTxt);
        char* match = strtok(cmdLineCopy, " ");
     // First, count the number of arguments
        while(match != NULL){
            count++;
            match = strtok(NULL, " ");
        }
    
        *argv = malloc(sizeof(char*) * (count+1));
        (*argv)[count] = 0;
        **argv = strdup("test"); // The program name would normally go in here
    
        if (count > 1){
            int i=1;
            cmdLineCopy = strdupa(cmdLineTxt);
            match = strtok(cmdLineCopy, " ");
            do{
                (*argv)[i++] = strdup(match);
                match = strtok(NULL, " ");
            } while(match != NULL);
         }
    
        *argc = count;
    }
    

提交回复
热议问题