diff --git a/config_ini/conf.c b/config_ini/conf.c index 48b5b8f..1ed15e7 100644 --- a/config_ini/conf.c +++ b/config_ini/conf.c @@ -57,6 +57,13 @@ Config *config_load(const char *filename) { return cfg; } +ConfigEntry *config_get_next(ConfigEntry *entry, int *index) { + if (!entry) + return NULL; + + return (0 == (*index)++) ? entry : entry->next; +} + /* Get value for a key */ const char *config_get(Config *cfg, const char *key) { for (ConfigEntry *e = cfg->head; e; e = e->next) { diff --git a/config_ini/conf.h b/config_ini/conf.h index 415a7e0..e25470c 100644 --- a/config_ini/conf.h +++ b/config_ini/conf.h @@ -11,8 +11,9 @@ typedef struct { ConfigEntry *head; } Config; -Config *config_load(const char *filename); -const char *config_get(Config *cfg, const char *key); -void config_free(Config *cfg); +Config *config_load(const char *filename); +const char *config_get(Config *cfg, const char *key); +ConfigEntry *config_get_next(ConfigEntry *entry, int *index); +void config_free(Config *cfg); #endif // CONF_H diff --git a/config_ini/main.c b/config_ini/main.c index b21a06f..32b0a55 100644 --- a/config_ini/main.c +++ b/config_ini/main.c @@ -1,8 +1,53 @@ #include "conf.h" +#include #include +#include +#include +#include -// Example usage int main(void) { + const char *home = getenv("HOME"); + if (!home) { + perror("home"); + exit(EXIT_FAILURE); + } + + /* Potentially scope this to preserve stack if thats an issue */ + char config_dir[256]; + char config_file[512]; + + { + snprintf(config_dir, sizeof(config_dir), "%s/.config", home); + snprintf(config_file, sizeof(config_file), "%s/mytool.ini", config_dir); + + /* Ensure ~/.config exists */ + struct stat st; + if (stat(config_dir, &st) == 0) { + if (!S_ISDIR(st.st_mode)) { + printf("Creating config directory\n"); + mkdir(config_dir, 0700); + perror("mkdir ~/.config"); + } + } + + /* Create config file */ + int fd = open(config_file, O_RDWR | O_CREAT, 0600); + if (fd < 0) { + perror("open mytool.ini"); + return 1; + } + close(fd); + } + + FILE *f = fopen(config_file, "r"); + if (!f) { + perror("fopen"); + return 1; + } + /* Parsing here ... */ + fclose(f); + unlink(config_file); + Config *cfg = config_load("config.ini"); if (!cfg) { fprintf(stderr, "Failed to load config.ini\n"); @@ -15,6 +60,15 @@ int main(void) { printf("Username: %s\n", user ? user : "(not set)"); printf("Password: %s\n", pass ? pass : "(not set)"); + printf("-----\n"); + + /* Iterate over config values */ + ConfigEntry *c = cfg->head; + int idx = 0; + while ((c = config_get_next(c, &idx)) != NULL) { + printf("%s = %s\n", c->key, c->value); + } + config_free(cfg); return 0; }