Home > OS >  C Argv check which argv path came from what input
C Argv check which argv path came from what input

Time:08-09

If i input paths with wildcards as command line parameters, like:
testprogramm a* b*
and the directory contains the following content:
aa ab ba bb
my argv string will contain:
{"testprogramm","aa","ab","ba","bb"}

However, i want to differentiate between files that originated from the first argument (a*) and the second (b*), how do i do that? What i am searching for is a method that can tell me by the example above that "aa" and "ab" came from the first argument and "ba" and "bb" from the second.

I know that the cp.c commands can do this, but i couldn't figure out how, as the source code is quite nested.

Edit: standard copy (from gnu core utils) cannot differentiate, only embedded (shells, where programm and utils are the same file) can.

CodePudding user response:

./program a* "|" b*

And then search the delimiter from your program:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int group = 0;

    for (int i = 1; i < argc; i  )
    {
        if (strcmp(argv[i], "|") == 0)
        {
            group  ;
        }
        else
        {
            printf("group: %d file: %s\n", group, argv[i]);
        }
    }
    return 0;
}

The output is:

group: 0 file: aa
group: 0 file: ab
group: 1 file: ba
group: 1 file: bb

CodePudding user response:

There is no real solution to solve this problem, at least with bash, as the only information it provides about argv is argv itself and argc. However, as the input is sorted on a per argument base, you can check for the first argument is not sorted, so it could detect it the other way around (b* and a*) but there is no real solution unless changing from bash to an embedded util box like toybox or busybox.

  • Related