Parse string into argv/argc

前端 未结 13 819
生来不讨喜
生来不讨喜 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 07:58

    This one I wrote also considers quotes (but not nested)

    Feel free to contribute.

    /*
    Tokenize string considering also quotes.
    By Zibri 
    https://github.com/Zibri/tokenize
    */
    
    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
      char *str1, *token;
      int j;
      char *qstart = NULL;
      bool quoted = false;
    
      if (argc != 2) {
        fprintf(stderr, "Usage: %s string\n", argv[0]);
        exit(EXIT_FAILURE);
      }
    
      for (j = 1, str1 = argv[1];; j++, str1 = NULL) {
        token = strtok(str1, " ");
        if (token == NULL)
          break;
        if ((token[0] == 0x27) || (token[0] == 0x22)) {
          qstart = token + 1;
          quoted = true;
        }
        if ((token[strlen(token) - 1] == 0x27) || (token[strlen(token) - 1] == 0x22)) {
          quoted = false;
          token[strlen(token) - 1] = 0;
          printf("%d: %s\n", j, qstart);
        } else {
          if (quoted) {
            token[strlen(token)] = 0x20;
            j--;
          } else
            printf("%d: %s\n", j, token);
        }
      }
    
      if (quoted) {
        fprintf(stderr, "String quoting error\n");
        return EXIT_FAILURE;
      } else
        return EXIT_SUCCESS;
    }
    

    Example output:

    $ ./tokenize "1 2 3 '4 5 6' 7 8 \"test abc\" 10 11"
    1: 1
    2: 2
    3: 3
    4: 4 5 6
    5: 7
    6: 8
    7: test abc
    8: 10
    9: 11
    

提交回复
热议问题