QDNix
Quick’n’dirty *NIX
ed.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 
5 #ifndef ED_VERSION
6 # define ED_VERSION "1.0"
7 #endif /* !ED_VERSION */
8 
9 #define IS_OPTARG(a, s, l) a[1] == s || \
10  strcmp(a + 1, "-" l) == 0
11 
12 static const char *prg_name;
13 
14 void
15 version(void)
16 {
17  printf("%s v%s\n", prg_name, ED_VERSION);
18  printf("Copyright (C) 2022 d0p1\n");
19  printf("License BSD-3: <https://directory.fsf.org/wiki/License:BSD-3-Clause>\n");
20  printf("This is free software: you are free to change and redistribute it.\n");
21  printf("There is NO WARRANTY, to the extent permitted by law.\n");
22  exit(EXIT_SUCCESS);
23 }
24 
25 void
26 usage(FILE *out, int retval)
27 {
28  fprintf(out, "Usage: %s [OPTION]... [FILE]\n\n", prg_name);
29  fprintf(out, "Options:\n");
30  fprintf(out, "\t-h, --help\tdisplay this help and exit\n");
31  fprintf(out, "\t-V, --version\toutput version information and exit\n");
32 
33  exit(retval);
34 }
35 
36 size_t
37 parse_flags(int argc, char *const argv[])
38 {
39  int idx;
40 
41  for (idx = 0; idx < argc; idx++)
42  {
43  if (argv[idx][0] == '-')
44  {
45  if (IS_OPTARG(argv[idx], 'h', "help"))
46  {
47  usage(stdout, EXIT_SUCCESS);
48  }
49  else if (IS_OPTARG(argv[idx], 'V', "version"))
50  {
51  version();
52  }
53  else
54  {
55  usage(stderr, EXIT_FAILURE);
56  }
57  }
58  else
59  {
60  break;
61  }
62  }
63 
64  if (idx >= argc)
65  {
66  usage(stderr, EXIT_FAILURE);
67  }
68 
69  return (idx);
70 }
71 
72 int
73 main(int argc, char *const argv[])
74 {
75  size_t idx;
76 
77  prg_name = *argv++; /* save and skip program name */
78  argc--;
79 
80  idx = parse_flags(argc, argv);
81  (void)idx;
82  return (EXIT_SUCCESS);
83 }