I am writing a program in C which is like a console so that user can specify different commands to be executed(which are also defined by me). Just like the one below:
>cmd1 arg
(result blah blah blah)
>
and I want to display usage info which is like:
>help
Usage: cmd1 arg1 [arg2]
cmd2 arg1 [arg2]
cmd3 arg1 [arg2]
....
But I find it clumsy to define string or macro like "Usage: cmd1 arg1 [arg2] \n \t "... (and I am not sure it's OK or not).
Is there some best practice to do so?
The standard practice is to make a usage function that you can call when certain conditions are met (there were no arguments pass to the program, etc), like this:
void usage(void) {
printf("Usage: cmd1 arg1 [arg2]\n"
" cmd2 arg1 [arg2]\n"
" cmd3 arg1 [arg2]\n"
...
" cmdn arg1 [arg2]\n"); // if the string is too long you'll have
// to break it up into multiple printfs
}
int main(int argc, char** argv) {
if (argc < 2) {
usage();
return 0;
}
// main program....
}
If you're programming on/for a system that can use the gnu argp library, you'd do well to look into that. It makes it easier to process the arguments, and creates help/usage messages and options for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With