I am looking for an example of a simple app that will use printf
to express two different strings based on a positional parameter.
In bash
I would use:
case $1 in
-h | --help ) showHelp
exit
;;
* ) manPipe
exit 1
esac
And prior to this I would list that a function called showHelp
would be called if the operater types either $ foo -h
or $ foo -help
into the Terminal. Anything else like $ foo -bar
would request that the function manPipe
would get called.
I have this code so far:
#include <stdio.h>
#include <cstring>
int secretFunction() {
printf("Success! You found the secret message!");
}
int main() {
str posParam;
posParam = X;
printf("Enter a number:");
scanf("%s",&posParam);
if ( posParam == "X" ){
printf("Welcome to app!\nType: " + $0 + " t\nto show a message");
}else{
if (posParam == "t" ){
secretFunction();
}
return 0;
}
return 0;
I know this code is really crappy, I was trying to make an example of the above code in bash. I am not trying to convert a bash script
into a C app
, I'm trying to play around with it. I drew the idea of something I want to work on from the Wikipedia article on the MD5 checksum C app
that takes a string and calculates the MD5 checksum for it. I cannot seem to work out what part they get the positional parameter to pass to the application.
This is a little different, I do understand, because it has prompted the user to provide an answer and then assign it to a value. I would rather use it as a positional parameter in the first instance.
What is $1
in Bash (et al) is argv[1]
in a C program:
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc > 1)
{
printf("You provided at least one argument (or parameter)\n");
printf("The first argument is \"%s\"\n", argv[1]);
}
return 0;
}
The argument argc
is the number of valid entries in the argv
array. argv[0]
is the executable name, and you can access up to argv[argc - 1]
. (Actually you can access argv[argv]
as well, it is always a NULL
pointer).