clinked-liststrsep

C - strsep splitting strings


I created a parseCmd method for my simpleShell program in C, and store each argument before a delimiter whitespace to be stored in my args[] array. However, I am trying to add arguments with their respective parameters into a linked list, but I am having trouble obtaining them.

For example, if I type ls, I want:

args[0] = "ls";

And when I type ls -l, I want;

args[0] = "ls";
args[1] = "-l";

What I am trying to do here is: if a "-" argument is detected, append it to the previous argument "ls" and save as a separate string "ls -l" to be stored into a linkedList (already implemented).

Here is my method.

void parseCmd(char* cmd, char** args)
{       
    int i;

    for(i = 0; i < MAX_LINE; i++) {
        args[i] = strsep(&cmd, " ");

        if (args[i] != NULL)
            printf("--> %s \n",args[i]);

        if(args[i] == NULL) break;
    }
}

EDIT:

I tried the following

if (strchr(args[i], '-'))
    printf("--> %s \n", args[i]);

But I am getting a seg fault.


Solution

  • String is an array of characters. You realize that args is a char**, so basically it is an array of arrays. You can check if args entry contains '-', if it is true then you can do a simple string concat and add that value to args. Check the value of the first character of string.

    Programmatically,

    if(args[i][0] == '-')
        <Insert code for concatenation>