Created
March 3, 2010 10:01
-
-
Save ByteProject/320490 to your computer and use it in GitHub Desktop.
template for a switchable command line utility (portable C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* switchtemp.c | |
* | |
* Coded by Stefan Vogt, revised Feb 19, 2011. | |
* Released under the FreeBSD license. | |
* http://www.byteproject.net | |
* | |
* template for a switchable command line utility | |
* | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define VERSION "[version 1.0]" | |
#define FALSE 0 | |
#define TRUE 1 | |
#define SWITCHCOUNT 2 | |
// basic function | |
void function(void) { | |
printf("\nYour function output!\n\n"); | |
} | |
/* help output */ | |
void show_help(void) { | |
printf("\nUsage: switchtemp -[SWITCH] \n"\ | |
"Placeholder for help text or app description.\n"\ | |
"Please use one of the following switches:\n\n"\ | |
"\t-f function\n"\ | |
"\t-h help\n"\ | |
"\t-v version\n\n"); | |
} | |
/* Valid switch given? */ | |
int getopt(const char *argument, const char *option) { | |
if( argument[0]=='-' && argument[1]==option[0] ) | |
return TRUE; | |
return FALSE; | |
} | |
int main (int argc, const char * argv[]) { | |
/* Call without a switch or with switch 'h'? */ | |
if(argc == 1 || getopt(argv[1],"h") == TRUE ) { | |
show_help(); | |
return EXIT_FAILURE; | |
} | |
/* shows the application version */ | |
else if(getopt(argv[1],"v") == TRUE) { | |
printf("\n" VERSION "\n\n"); | |
return EXIT_SUCCESS; | |
} | |
/* Switch 'f' and the correct amount of arguments? */ | |
else if(getopt(argv[1],"f") == TRUE && | |
(argc < SWITCHCOUNT || argc > SWITCHCOUNT) != TRUE) { | |
function(); | |
} | |
/* all other cases */ | |
else { | |
show_help(); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment