[techtalk] switch function in C (or how to read commandline args?)
JamesA.Sutherland
JamesA.Sutherland
Sat Jun 30 21:55:07 EST 2001
On Sat, 30 Jun 2001 21:32:38 +0100, you wrote:
>I want to read a bunch of commandline args or config options from file
>in a C program. Now, in bash, I can use a switch structure to do stuff
>based on the *string* presented. AFAIR, in C, you can only switch on an
>*int*.
>
>So, how do I use a switch to process my config options? Or do I have to
>build an "if; elseif; else" ladder instead? I have options in a config
>file that look like
>
><opt> <arg>
>location Belmullet
>name "Joe Bloggs"
>
>and commandline switches like
>
>--force
>-C /path/to/config.file
>
>I can read these and put the values into "opt" and "arg" but what I need
>to do next is the C equivalent to the following (bash)
>
>case $opt in
> name)
> NAME=$arg
> ;;
> location)
> LOCATION=$arg
> ;;
> --force)
> FORCE=TRUE
> ;;
> -C)
> CONFIG_FILE=$arg
> readconfig($CONFIG_FILE)
> ;;
> *)
> echo "AARRRGGGHHHH!!!!!"
> ;;
>esac
>
>I even tried
>
>case (! strcmp(opt,"config-file")):
>
>to try and return an integer for the case statement but it
>seems to need a constant rather than the return value from
>function to work properly.
Unfortunately, C can't do this in a very nice way. As you've seen,
each case statement will only work with a constant - a single
character, or a number. What you can do is switch() on the FIRST
character of the word, then use strcmp() to check for each possibility
- something like this:
#include <string.h>
int main(int argc, char* argv[])
{
if (argc != 2)
return 0;
switch(*argv[1])
{
case 'f':
if (!strcmp("foo",argv[1]))
printf("foo\n");
if (!strcmp("far",argv[1]))
printf("far\n");
break;
default:
break;
}
return 0;
}
This takes "foo" and "far" as being valid statements, and just prints
them; anything else is just ignored. Obviously, if you had lots of
statements starting with the same character (like all the --enable...
options for GNU autoconf's configure scripts) you can use a second or
third level of switch() statements.
It would be nice if C could be used with case "foo", but I suppose
implementing that efficiently would have been too stressfull for the
original C compilers?
You can do something similar using the GNU getopt library, I think,
but I haven't looked very closely at that - and besides, hand-rolling
code is much more rewarding ;-)
James.
More information about the Techtalk
mailing list