jdoe jdoe - 4 days ago 5
C Question

Program parameters to main in c - ./dev --print

I am trying to make a program check whether the user is passing a program parameter when running the program. fx:

./dev --print


I came up with the following:

int main(int argc, char *argv[]) {
char print[] = "--print";
if(strcmp(argv[1], print) == 0) {
solve_a_bunch_of_functions_and_print_without_user_input();
}
else {
ask_for_user_input();
then_solve_bunch_of_functions();
}
}


Is this the correct / smartest way to do so?

Currently I am experiencing issues with seg-faults after this implementation for everytime i get into the else statement. Not sure my implementation here has anything to do with it.

Answer

Yes, that's one way although I think most C programmers wouldn't bother with the separate variable, and just do:

if(strcmp(argv[1], "--print") == 0)

Of course, you should first validate that there is an argument in argv[1], by checking argc, too. Otherwise you're passing NULL to strcmp(), which is a bad idea.

if(argc > 1 && strcmp(argv[1], "--print") == 0)
{
}
Comments