jdoe jdoe - 1 year ago 81
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) {
else {

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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download