Sarp Kaya
Sarp Kaya

Reputation: 3784

How to compare string command line arguments in C?

Sorry, I'm a rookie in C. What I am trying to do is just to print something if --help parameter is entered to the terminal like ./program --help. So the code is this:

char *HELP = "--help";
char *argv1 = argv[1];

if (argv1 == HELP) {
    printf("argv[1] result isaa %s\n", argv[1]);
}

So even if I use --help parameter it does not pass through the if condition. So what could be the reason behind that?

Upvotes: 4

Views: 13997

Answers (6)

agit
agit

Reputation: 631

I had same problem. my problem is solved by using strncmp.
strcmp doesnt work for my problem anyway

#include <string.h>


    if (strncmp(argv1, HELP,6) == 0) //6 is size of argument
    {
    //do smt
    }

Upvotes: 0

rashok
rashok

Reputation: 13434

char *HELP = "--help"; - Here --help is a string literal which is a read only data in text segment. You are just assining the address to the pointer variable HELP.

`argv[1] will given you the address where the first commandline arguemet is stored.

So argv[1] and HELP are having different address. So the condition (argv[1] == HELP) is just checking the address stored in these two pointer variables. Always this will fail.

Actually you have to compare the content of these two pionters. For this you can impelement the string compare logic or use the strcmp function.

if (0 == strcmp(argv[1], HELP)
{
    //do your stuff
}

Upvotes: 0

cnicutar
cnicutar

Reputation: 182649

That's not how you compare strings in C. Use strcmp or strncmp:

if (strcmp(argv1, HELP) == 0)

Include string.h to get access to those.

Upvotes: 12

blfuentes
blfuentes

Reputation: 2827

You shoul use strcmp.

result=strcmp(argv1,HELP);
if(result==0)
{
    --what you want
}

Upvotes: 0

Spidey
Spidey

Reputation: 2589

In C, there is no string type. You've declared char *HELP, so HELP is a char *, not a string. In the if, you are comparing two pointers, instead of the string they point to. You will want to call strcmp (string compare), a function that receives two char *, and compares the strings pointed by them.

Upvotes: 3

hmjd
hmjd

Reputation: 121971

That is comparing the addresses, not the content. Use strcmp():

if (0 == strcmp(HELP, argv1))
{
    printf("argv[1] result isaa %s\n", argv[1]);
}

Be sure and check that argc > 1 before accessing argv[1].

Upvotes: 4

Related Questions