0

I'm new to C and doing the implementation of shell. Now I'm struggling with the following question

There is a 2D char array. argv[0] contains "ls -l < test".

Then I want to use < to be the delimiter. When it's divided, I want to store the first part("ls -l") and second part("test") into two different new char array.

In my code, this is the implementation of IO redirection. I can only provide the part of the code as this is an assignment.

This is what I have so far.

while (argv[num_cmds]!=NULL )
    {    // go though the current char array, check if there is a '<'
        for(int i=0;i<strlen(argv[num_cmds]);i++){

            if(argv[num_cmds][i]=='<'){
                //first half
                strcpy(cmds[num_cmds],strtok(argv[num_cmds], in)); 

                //second half, not yet implemented
            }
    }

Now cmd[0] contains the first half. But I still need to deal with the second half. If my code structure is not doable, I'm happy to know the better method

Apologise in advance for my English

  • If you are talking about the `argv` variable from your `main` function, then `argv[0]` probably does not contain "ls -l < test". Instead, `argv` most likely contains "ls", "-l", "<" and "test" in cells `[0]`, `[1]`, `[2]` and `[3]`. Correct me if I'm wrong but to me it really looks like that. Then, along with `argv`, the first argument of your `main` function is `argc`, and it contains the number of parameters passed when you called the program, so here it's 4 (0, 1, 2 and 3). You could loop on `argc`'s value instead of checking `argv`'s pointer value. Hope this helps. – deqyra Jun 06 '16 at 18:09
  • And to answer the original question, you can retrieve the second half with `strcpy(secondHalf, (argv[num_cmds]) + i + 1);`. `argv[num_cmds]` is a pointer to the beginning of the string, right ? So you just have to shift the pointer value by the number of characters you want to skip, which is `i + 1`, to get a pointer to the beginning of the second half of the string. – deqyra Jun 06 '16 at 18:16
  • @qreon - the OP will only get "ls" and "-l", the "<" and "test" will be intercepted by the shell – KevinDTimm Jun 06 '16 at 19:23
  • @qreon strcpy(secondHalf, (argv[num_cmds]) + i + 1) is the exactly answer I want. Thank you! – Zack Chen Jun 07 '16 at 04:56
  • @ZackChen You're welcome. If you want to trim the retrieved strings, you can take a look here http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way – deqyra Jun 08 '16 at 09:44

0 Answers0