Search code examples
cshellparsingcommandansi-c

Parsing commands shell-like in C


I want to parse user input commands in my C (just C) program. Sample commands:

add node ID

add arc ID from ID to ID

print

exit

and so on. Then I want to do some validation with IDs and forward them to specified functions. Functions and validations are of course ready. It's all about parsing and matching functions...

I've made it with many ifs and strtoks, but I'm sure it's not the best way... Any ideas (libs)?


Solution

  • I think what you want is something like this:

    while (1) 
    {
        char *line = malloc(128); // we need to be able to increase the pointer
        char *origLine = line;
        fgets(line, 128, stdin);
    
        char command[20];
        sscanf(line, "%20s ", command);
    
        line = strchr(line, ' ');
    
        printf("The Command is: %s\n", command);
    
        unsigned argumentsCount = 0;
        char **arguments = malloc(sizeof(char *));
    
        while (1)
        {
            char arg[20];
            if (line && (sscanf(++line, "%20s", arg) == 1))
            {
                arguments[argumentsCount] = malloc(sizeof(char) * 20);
                strncpy(arguments[argumentsCount], arg, 20);
    
                argumentsCount++;
    
                arguments = realloc(arguments, sizeof(char *) * argumentsCount + 1);
                line = strchr(line, ' ');
            }
            else {
                break;
            }
        }
    
        for (int i = 0; i < argumentsCount; i++) {
            printf("Argument %i is: %s\n", i, arguments[i]);
        }
    
        for (int i = 0; i < argumentsCount; i++) {
            free(arguments[i]);
        }
    
        free(arguments);
        free(origLine);
    }  
    

    You can do what you wish with 'command' and 'arguments' just before you free it all.