matt/src/args.c

92 lines
1.9 KiB
C
Raw Normal View History

2024-07-16 17:37:46 +00:00
#include <libmp/all.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "args.h"
#include "util.h"
void args_add(args_t *args, char *name){
if(NULL == args->list)
args->list = malloc(sizeof(arg_t)*(args->count+1));
else
args->list = realloc(args->list, sizeof(arg_t)*(args->count+1));
args->list[args->count].name = name;
args->list[args->count++].value = NULL;
}
void args_add_value(args_t *args, char *value){
if(NULL != args->list && args->list[args->count-1].value == NULL){
args->list[args->count-1].value = value;
return;
}
if(NULL == args->list)
args->list = malloc(sizeof(arg_t)*(args->count+1));
else
args->list = realloc(args->list, sizeof(arg_t)*(args->count+1));
args->list[args->count].name = NULL;
args->list[args->count++].value = value;
}
args_t *args_parse(int argc, char *argv[]){
args_t *args = malloc(sizeof(args_t));
bzero(args, sizeof(args_t));
if(argc <= 1)
return args;
for(int i = 1; i < argc; i++){
if(startswith(argv[i], "--"))
args_add(args, argv[i]+2);
else
args_add_value(args, argv[i]);
}
return args;
}
void args_free(args_t *args){
free(args->list);
free(args);
}
char *args_get_string(args_t *args, char *name){
for(int i = 0; i < args->count; i++){
if(NULL == args->list[i].name)
continue;
if(eq(args->list[i].name, name))
return args->list[i].value;
}
return NULL;
}
bool args_get_bool(args_t *args, char *name){
for(int i = 0; i < args->count; i++){
if(NULL == args->list[i].name)
continue;
if(eq(args->list[i].name, name))
return true;
}
return false;
}
int args_get_int(args_t *args, char *name){
for(int i = 0; i < args->count; i++){
if(NULL == args->list[i].name)
continue;
if(eq(args->list[i].name, name))
return atoi(args->list[i].value);
}
return -1;
}