From d3dfdb77779004950cf3afb19e456b7d5c39c940 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Mon, 30 Jan 2023 03:17:30 +0000 Subject: [PATCH] networkd: Implement writing configuration files Signed-off-by: Michael Tremer --- src/networkd/config.c | 40 ++++++++++++++++++++++++++++++++++++++++ src/networkd/config.h | 3 +++ 2 files changed, 43 insertions(+) diff --git a/src/networkd/config.c b/src/networkd/config.c index a3db7c65..b2a23f00 100644 --- a/src/networkd/config.c +++ b/src/networkd/config.c @@ -165,6 +165,46 @@ ERROR: return r; } +int nw_config_writef(struct nw_config* config, FILE* f) { + struct nw_config_entry* entry = NULL; + int r; + + STAILQ_FOREACH(entry, &config->entries, nodes) { + // Skip if value is NULL + if (!*entry->value) + continue; + + // Write the entry + r = fprintf(f, "%s=\"%s\"\n", entry->key, entry->value); + if (r < 0) { + ERROR("Failed to write configuration: %m\n"); + return r; + } + } + + return 0; +} + +int nw_config_write(struct nw_config* config, const char* path) { + int r; + + FILE* f = fopen(path, "w"); + if (!f) { + ERROR("Failed to open %s for writing: %m\n", path); + r = 1; + goto ERROR; + } + + // Write configuration + r = nw_config_writef(config, f); + +ERROR: + if (f) + fclose(f); + + return r; +} + static struct nw_config_entry* nw_config_find(struct nw_config* config, const char* key) { struct nw_config_entry* entry = NULL; diff --git a/src/networkd/config.h b/src/networkd/config.h index c5a2f7f2..90e73f4b 100644 --- a/src/networkd/config.h +++ b/src/networkd/config.h @@ -34,6 +34,9 @@ struct nw_config* nw_config_unref(struct nw_config* config); int nw_config_readf(struct nw_config** config, FILE* f); int nw_config_read(struct nw_config** config, const char* path); +int nw_config_writef(struct nw_config* config, FILE* f); +int nw_config_write(struct nw_config* config, const char* path); + int nw_config_del(struct nw_config* config, const char* key); int nw_config_set(struct nw_config* config, const char* key, const char* value); -- 2.47.3