Skip to content

Instantly share code, notes, and snippets.

@tuxillo
Created December 30, 2013 18:23
Show Gist options
  • Save tuxillo/8185742 to your computer and use it in GitHub Desktop.
Save tuxillo/8185742 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define WS " \t\r\n"
#define LIBHAMMER_MAXCFGOPTS 6
#define TOSTR(n) #n
enum libhammer_cfglist {
snapshots_cfg,
prune_cfg,
rebalance_cfg,
dedup_cfg,
reblock_cfg,
recopy_cfg
};
struct libhammer_pfs_confopt {
char *optname;
char *args[3];
};
typedef struct libhammer_pfs_config {
struct libhammer_pfs_confopt opts[LIBHAMMER_MAXCFGOPTS];
} *libhammer_pfs_config_t;
static int
str2idx(const char *opt)
{
if (strcmp("snapshots", opt) == 0)
return snapshots_cfg;
else if (strcmp("prune", opt) == 0)
return prune_cfg;
else if (strcmp("rebalance", opt) == 0)
return rebalance_cfg;
else if (strcmp("dedup", opt) == 0)
return dedup_cfg;
else if (strcmp("reblock", opt) == 0)
return reblock_cfg;
else if (strcmp("recopy", opt) == 0)
return recopy_cfg;
else
return -1;
}
int
parse_config_file(char *text, libhammer_pfs_config_t config)
{
char *line, *tok, *tok2;
int i;
int idx;
while ((line = strsep(&text, "\n")) != NULL) {
if (line[0] != '#') {
tok = strsep(&line, WS);
idx = str2idx(tok);
config->opts[idx].optname = tok;
/*
* Attempt to extract all the arguments for the
* current option being parsed. Since there can
* be multiple spaces between the option and its
* arguments, multiple strsep() calls are needed
* when that is detected.
*/
for (i = 0; i < 3; i++) {
tok2 = strsep(&line, WS);
while(tok2 && tok2[0] == '\0')
tok2 = strsep(&line, WS);
if (!tok2)
break;
config->opts[idx].args[i] = tok2;
}
}
}
return 0;
}
void
print_config(libhammer_pfs_config_t config)
{
int i, j;
for (i = 0; i < LIBHAMMER_MAXCFGOPTS; i++) {
fprintf(stdout, "_%s ", config->opts[i].optname);
for (j = 0; j < 3; j++)
fprintf(stdout, "_%s ", config->opts[i].args[j]);
printf("\n");
}
}
int
main(void)
{
libhammer_pfs_config_t config;
FILE *fp;
char text[1024];
config = malloc(sizeof(*config));
fp = fopen("./config.txt", "r");
fread(text, 1, 1023, fp);
parse_config_file(text, config);
print_config(config);
free(config);
fclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment