Created
October 20, 2022 06:51
-
-
Save collindonnell/b50f16d0e9dba1069e423a59dec98865 to your computer and use it in GitHub Desktop.
Simple command line tool in C which uses getopt_long
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
#include <stdio.h> | |
#include <ctype.h> | |
#include <stdbool.h> | |
#include <stdlib.h> | |
#include <getopt.h> | |
#include <string.h> | |
static struct config { | |
bool yell; | |
} cfg; | |
static struct option long_options[] = { | |
{"help", no_argument, NULL, 'h'}, | |
{"yell", no_argument, NULL, 'y'} | |
}; | |
static int parse_args(struct config *cfg, int argc, char *argv[]); | |
static void help() { | |
printf("Usage: speak [options] \n" | |
" -y, --yell Echo the input loudly\n" | |
" -h, --help Show this help \n"); | |
} | |
int main(int argc, char *argv[]) { | |
if (parse_args(&cfg, argc, argv)) { | |
help(); | |
exit(1); | |
} | |
int c; | |
while ((c = fgetc(stdin)) != EOF) { | |
if (cfg.yell) { | |
putc(toupper(c), stdout); | |
} else { | |
putc(c, stdout); | |
} | |
} | |
return 0; | |
} | |
static int parse_args(struct config *cfg, int argc, char *argv[]) { | |
int c; | |
memset(cfg, 0, sizeof(struct config)); | |
while ((c = getopt_long(argc, argv, "hy", long_options, NULL)) != -1) { | |
switch (c) { | |
case 'h': | |
help(); | |
exit(0); | |
break; | |
case 'y': | |
cfg->yell = true; | |
break; | |
default: | |
return -1; | |
break; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment