Config iteration

This commit is contained in:
Imbus 2025-11-14 20:15:27 +01:00
parent ac6abd7c10
commit 77fd1763e0
3 changed files with 66 additions and 4 deletions

View file

@ -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) {

View file

@ -13,6 +13,7 @@ typedef struct {
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

View file

@ -1,8 +1,53 @@
#include "conf.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
// 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;
}