CPlay/config_ini/main.c
2025-11-14 20:15:27 +01:00

74 lines
1.8 KiB
C

#include "conf.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
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");
return 1;
}
const char *user = config_get(cfg, "username");
const char *pass = config_get(cfg, "password");
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;
}