file-handling · intermediate · ~15 min
Stateful line-by-line config parsing.
Look up a value in INI/conf text by [section] and key — stateful line parsing that drives countless tools' config loaders.
Implement int ini_get(const char *ini, const char *section, const char *key, char *out, size_t cap) that finds the key=value line for key inside the [section] block and copies its value into out (NUL-terminated, bounded by cap).
ini: newline-separated config text with [section] headers and key=value lines.section: the section name to search within (without brackets).key: the key whose value you want (exact match).out / cap: destination buffer and its size.Return the length of the value written to out. Return -1 if the key isn't found in that section, the value doesn't fit in cap, or any pointer arg is NULL.
ini = "[server]\nhost=localhost\nport=8080\n[auth]\nuser=admin\n"
ini_get(ini, "server", "host", out, 64) -> 9, out = "localhost"
ini_get(ini, "auth", "user", out, 64) -> 5, out = "admin"
ini_get(ini, "server", "user", out, 64) -> -1 (key is in [auth], not [server])
[...] headers; match the key by exact length, not prefix. Bound the copy by cap.INI/conf files drive countless tools. Looking up [section] key=value teaches stateful line parsing.
ini: config text. section/key: lookup target. out/cap: result buffer and size.
int length of the value copied to out, or -1 if not found / overflow / NULL.
Stateful: track [section]; match keys exactly, only within the right section.
#include <stddef.h>
int ini_get(const char *ini, const char *section, const char *key, char *out, size_t cap) {
/* TODO */
(void)ini; (void)section; (void)key; (void)out; (void)cap;
return -1;
}
Matching a key in the wrong section. Prefix-matching keys (use exact length). Forgetting the overflow guard.
Same key in two sections. Missing key. Section with no such key.
O(text length).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.