Home > front end >  How do I read after a specific character from argv[] in C?
How do I read after a specific character from argv[] in C?

Time:09-30

So my goal is to mimic the pipe ( | ) operator used in the terminal, in C. Basically I'm making a pipe for the left and right argument.

In the terminal the run is done as such;

./run ls : sort

Where 'ls' will pipe the data into 'sort'. And ' : ' is used to denote the left and right arguments. I have it working where if I just type, "./run ls :" or "./run ls" it does what 'ls' should do, including parameters, if passed.

To read argv up to the " : ", I'm doing this:

int i;
char *command1[argc];

  for (i = 0; i < argc; i  ) {
    if (strcmp(argv[i], ":") == 0) break;
      command1[i] = argv[i];
  }

Then whatever is in command1[1] will be used in execlp() to run the command, which works.

My next problem is to figure out how to read from argv to get the command and arguments of everything after " : ".

I'm just not sure how I should read the argv, then store everything into a new array that exits after the colon.

CodePudding user response:

Use two loops, one reading up to the :, and the second reading after the :.

int k = 0;
int i;
char *command1[argc];
char *command2[argc];

for (i = 1; i < argc && strcmp(argv[i], ":") != 0; i  ) {
    command1[k  ] = argv[i];
}
command[k] = NULL;

k = 0;
i  ; // move past the ":"
for (; i < argc && strcmp(argv[i], ":") != 0; i  ) {
    command2[k  ] = argv[i];
}
command2[k] = NULL;

Notice that I used a separate variable k for the index into the array I'm copying into, so I can start it from 0, not use the same index as in argv.

CodePudding user response:

int inargs(char *str, int argc, char *argv[], int numchars)
{
    /* If search partial string specify numchars, else 0 */
    int i;

    for (i = 0; i < argc; i  )
    {
        if (numchars == 0)
        {
            if (strcmp(str, argv[i]) == 0)
                return i;
        }
        else
        {
            if (strncmp(str, argv[i], numchars) == 0)
                return i;
        }
    }

    return -1;
}

int main(int argc, char *argv[])
{
    int semiColPos;
    char *strAfterSemiCol;
        
    if ((semiColPos = inargs(":", argc, argv, 0)) > -1)
    {
        strAfterSemiCol = argv[semiColPos   1];
        puts(strAfterSemiCol);
    }

    return 0;
}

Command line (assuming prog name is 'run':

./run ls : sort

"sort" or whatever was after ":" is returned.

./run ls do other things : sort and other stuff

...also "sort" in is returned...

  • Related