How to get all text after specific char?
I wrote a little program which prints help information if argument is not passed.
If I run the app without arguments
./myApp
it pr开发者_开发知识库ints
./myApp --filename=file
I know that argv[1] holds the first parameter, but I can't figure out how to fetch the text after "=" ie the name of file.
Instead of parsing the string manually, you should rather use getopt()
or getopt_long()
.
They do the dirty work for you and behave in the way people expect it (while self-written parsers are sometimes confusing - some use --arg value
, others --arg=value
, some even use -arg value
)
You'll have to parse it yourself. strtok
is very useful for that, another one is strstr
. There are also some ready libraries which allow you importing this functionality into your project, if you don't want to write it all yourself, like this one for example.
strchr()
returns a pointer to the character. The next characters are what you want
char *equals;
equals = strchr(argv[1], '=');
if (equals) {
printf("Rest of argument: %s\n", equals + 1);
} else {
printf("No equal found in argv[1] (%s)\n", argv[1]);
}
Depending on your specific needs, you may want to copy them somewhere or just use them right from the argv[1] argument.
Use strchr-function to find the '=' character. Check the strchr return value. If return value is non-NULL, increment it by one and you have what you want.
Instead of parsing the stuff yourself you could use argp the libc argument-parser:
http://www.gnu.org/s/hello/manual/libc/Argp.html
The strings in Argv is separated by whitespaces, so you would have to parse the argv[1] string to fetch the text after '='. However there is some functions called getopt()
and getopt_long()
, that are part of the POSIX standard.
If this functions are available to you, you can use getopt_long()
to get both the short, and the long options (e.g. filename), and its argument (e.g. file).
Link includes explanations and examples: http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_22.html
精彩评论