Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
Sarp Kaya Avatar asked Dec 01 '22 23:12

Sarp Kaya


2 Answers

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.

like image 126
cnicutar Avatar answered Dec 05 '22 00:12

cnicutar


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].

like image 43
hmjd Avatar answered Dec 05 '22 01:12

hmjd