-
Command line arguments.
Hi, I'm a bit of a newbie, I am doing a project for school and it needs to accept command line arguments. I know that I need to use argc and argv the problem is I need to be able to use anything from 1 switch to 3 switches, example 'finds -e bal input.cpp' or 'finds -e -g -f bal input.cpp' or 'finds -egf bal input.cpp' any of them are valid. The problem is how do I know which values in the array argv are switches, should I use a for loop searching for - as value 0, or what.
Thanks for your help in advance. Sorry about the burbling.
-
One way is just to test for each one. Or if u want to test the input to see if it's a file then try to open the argument name using fopen() and see if it returns NULL.
-
Hmmm, but argv[0] is the program name, and 'bal' is what it is searching for inside the file input.cpp. I just want to be able to get the - switches. Thanks anyway.
-
argc is an integer telling you how many arguments you have. Just use that to set up a loop, than go through the *argv array and incrment each one until you get to a '/0'. Read each of those characters of the string into a new one your program can use just like a string, then test the first characters of each one to see if they're a switch. If they match a cetain profile, tne call the function to do what you want to do.
-
You do not have to test for /0 using C with argv and argc. The number in argc is the last command line argument there is.
So if argc is 3, there are 3 command line arguments since arg[0] is the program name itself.
-
Ok, thanks for all your help, but the problem is, there can be anywhere from 1 to 3 switches, and I need to find out whether the switches are valid, for example, -e -f -g are all valid, yet so is -ef or -efg or -eg, if they pass 'find -e bal input.cpp' it has 1 argument at slot argv[1], but 'find -e -f bal input.cpp' has 2 switches at argv[1] and argv[2], problem is also 'find -ef bal input.cpp' is also valid, with 2 switches at argv[1]. I need to validate the input before I can continue the program. How can I filter the switches, to make sure only valid switches are passed to the program.
Hope this explains my delima a little better. Thanks for your help.
-
You are probably gonna wanna use a for loop controled by argc make strings out of all the arguments, and then test each string to see if is starts with a '-'. This will tell you which are switches. The program only sees letters, starting a switch with a dash is just convention, not something that is coded separatly.
-
First off, make a long string with all possible letters in it - for single letter switches. Then use a string function to compare the input string with your string. If one or more letters from the input string match your string, the switch is valid.
For word switches you will have to just test them against pre-sets within a switch() {} or something.