Parsing commandline arguments
This commit is contained in:
32
ulib/args/args.c
Normal file
32
ulib/args/args.c
Normal file
@ -0,0 +1,32 @@
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <args/args.h>
|
||||
#include <string/conv.h>
|
||||
#include <string/string.h>
|
||||
#include <uprintf.h>
|
||||
|
||||
int32_t parse_args(char **argv, size_t argc, Arg *defs) {
|
||||
for (size_t i = 0; i < argc; i++) {
|
||||
if (argv[i][0] == '-' && argv[i][1] != '\0') {
|
||||
char *optname = argv[i];
|
||||
size_t j = 0;
|
||||
while (!defs[j].end) {
|
||||
Arg *def = &defs[j];
|
||||
if (string_strcmp(def->shortname, optname) == 0) {
|
||||
if (i < argc - 1) {
|
||||
switch (def->expected_value) {
|
||||
case ARG_STRING:
|
||||
*((char **)def->ptr) = argv[i+1];
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
j++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ARGP_OK;
|
||||
}
|
33
ulib/args/args.h
Normal file
33
ulib/args/args.h
Normal file
@ -0,0 +1,33 @@
|
||||
#ifndef ULIB_ARGS_H_
|
||||
#define ULIB_ARGS_H_
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
char **args(void);
|
||||
size_t argslen(void);
|
||||
|
||||
typedef struct {
|
||||
char *shortname;
|
||||
enum { ARG_STRING } expected_value;
|
||||
void *ptr;
|
||||
bool end;
|
||||
} Arg;
|
||||
|
||||
#define ARG(sn, ev, p) ((Arg){ \
|
||||
.shortname = (sn), \
|
||||
.expected_value = (ev), \
|
||||
.ptr = (void *)(p), \
|
||||
.end = false, \
|
||||
})
|
||||
|
||||
#define ARG_END() ((Arg){ .end = true, })
|
||||
|
||||
enum {
|
||||
ARGP_OK = 0,
|
||||
};
|
||||
|
||||
int32_t parse_args(char **argv, size_t argc, Arg *defs);
|
||||
|
||||
#endif // ULIB_ARGS_H_
|
Reference in New Issue
Block a user