Link to home
Start Free TrialLog in
Avatar of tsurai
tsuraiFlag for United States of America

asked on

More on Argv

I'm trying to write my own clone of the UNIX utility Cut.  Syntax as follows:

cut sourcefile -c1,15

I'm still getting familiar with argv and handling arguments passed to it.  I realize that:
argv[0] = cut
argv[1] = sourcefile
argv[2] = -c1,15

When I'm processing the command line args, how can I check that argv[2] contains the "-c"?
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tsurai

ASKER

Correction:

argv[0] = cut
argv[1] = -c1,5
argv[2] = filename

So I'd use:
if( !strcmp("-c", argv[1], 1))
?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
PS: See also the function reference for 'strstr()' at bhttp://www.cplusplus.com/reference/clibrary/cstring/strstr.html
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> if( !strcmp("-c", argv[1], 1))

No :

        if (!strncmp("-c", argv[1], 2))

with strncmp instead of strcmp and 2 instead of 1 :

        http://www.cplusplus.com/reference/clibrary/cstring/strncmp.html

Btw, if you need to be able to recognize more command line options, then you probably want to parse it one character at a time :

        char *ptr = argv[1];
        if ('-' == *ptr) {
            /* command line option found */
            ++ptr;
            switch (*ptr) {
                case 'c' :
                    /* we found "-c", so (ptr+1) points to something like "1,5" */
                    break;
                /* other cases */
                default :
                    /* unsupported command line option */
                    break;
            }
        }
since '-' places in first position
if (argv[1][0] == '-')
...
>> if (argv[1][0] == '-')

That's what I had, no ?

        char *ptr = argv[1];
        if ('-' == *ptr)
Avatar of tsurai

ASKER

What's the difference between strncmp and !strncmp?
They are the same function, the ! means "not" or if the value returned is 0 (or false) then invert to non-zero (or true). In this case when strncmp returns 0 is means the strings being compared were equal so the if statement will need to evaluate to true when the strings are equal, so "!" was added to accomplish this.