add arg parser

Signed-off-by: AGentooCat <agentoocat@mail.i2p>
This commit is contained in:
2024-06-13 09:30:48 +00:00
parent bc642bae7c
commit 4441fb114e
4 changed files with 57 additions and 2 deletions

View File

@ -21,7 +21,7 @@ PROJ_LD =
# set the source files to be built for the program/library
# dont prefix src/ or src/lib/
PROG_SRCS=main.c
PROG_SRCS=main.c args.c
LIB_SRCS=
# what the program depends on (-l<ib>)

41
src/args.c Normal file
View File

@ -0,0 +1,41 @@
#include "args.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <err.h>
#define EMSG "failed to parse args: "
_Noreturn void print_help(char *argv0, int code) {
errx(code,
"itoomail " VERSION ", written by AGentooCat\n"
"USAGE: %s <-c config>\n"
" -c <config> : config file to use", argv0);
}
struct Args parse_args(int argc, char **argv) {
struct Args args;
memset(&args, 0, sizeof(args));
int opt;
while ((opt = getopt(argc, argv, ":c:h")) != -1) switch (opt) {
case 'c':
if (!(args.config = strdup(optarg)))
err(1, EMSG "couldn't allocate memory");
break;
case 'h':
print_help(argv[0], 0);
case ':':
errx(1, "missing argument to \"-%c\"", optopt);
case '?':
errx(1, "unknown argument to \"-%c\"", optopt);
}
if (!args.config)
errx(1, "no config file given");
return args;
}

12
src/args.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef ARGS_H
#define ARGS_H
#include <stdlib.h>
struct Args {
char *config;
};
struct Args parse_args(int argc, char **argv);
#endif

View File

@ -1,5 +1,7 @@
#include <stdio.h>
#include "args.h"
int main(int argc, char **argv) {
fprintf(stderr, "Hello world! argc=%d argv=%p\n", argc, argv);
struct Args args = parse_args(argc, argv);
fprintf(stderr, "Hello world! config=%s\n", args.config);
}