Emma Barrett Emma Barrett - 11 months ago 65
C Question

Checking for command line arguments in C

I wrote this code to take input from the command line, and depending on the input, will perform a set of actions, or if the input is incorrect, throws an error. However, I also need to check if no arguments are supplied, which I try to account for in my else statement.

if(strcmp(argv[1], "-L") == 0)
{
//does stuff
}


else if(strcmp(argv[1], "-W") == 0)
{

//does stuff

}

else if (*(argv[1]) != 1)
{
puts("error: invalid input");
}

else //should check if no arguments
{
puts("error: expected command line argument");
return 1;
}


I am getting a segmentation fault whenever there are no arguments from the command line, and I'm not sure how to fix it. I have also tried to write the else statement this way:

else if(argc < 2)
{
puts("error: expected command line argument");
return 1;
}


This was based on my previous research on here where I found "C produce error if no argument is given in command line," but it won't work either. I am a beginner in C and do not fully understand argc and argv, so if anyone has any suggestions or logic I'm completely overlooking, please let me know.

Answer Source

You need to check if argc < 2 before anything else.

Else you get segmentation fault because argv[index] could be something you have not priviledges to get.