What I am trying to do is take in command line arguments and change some variables according to the arguments. I have attached a chunk of my code because the whole code is ~400 lines.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char somestring[500];
int ca=0;
if (argc==1) //if no arguments are specified use defaults
{
}
else
{
while(ca<argc)
{
ca++
if(strcmp(argv[ca],"-f")==0)
{
printf("This works");
ca++;
if(strcmp(argv[ca],"red")==0){
printf("this will print red\n");
}
else{
printf("invalid color");
}
}
if(strcmp(argv[ca),"")==0)
{
printf("invalid argument");
}
else {
strcat(somestring,argv[ca]);
}
}
printf("%s",somestring);
}
}
If the user inputs:
./foobar -f red this is a string
the program should print:
"this will print red this is a string"
If the user inputs:
./foobar -f red
the program should print "invalid number of command line arguments".
What is the easiest way to do this? I have tried tons of possibilities with no luck. Varying number of arguments is the main problem for me (also I have more than 5 options e.g..-f -b -h -w -e)
Help would much appreciated. I can add my whole code if you want.