file-handling · intermediate · ~15 min

Read a value from INI text

Stateful line-by-line config parsing.

Challenge

Look up a value in INI/conf text by [section] and key — stateful line parsing that drives countless tools' config loaders.

Task

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).

Input

  • 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.

Output

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.

Example

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])

Edge cases

  • Same key name in two sections: return the one in the requested section.
  • Missing key, or section without that key: -1.

Rules

  • Track the current section from [...] headers; match the key by exact length, not prefix. Bound the copy by cap.

Why this matters

INI/conf files drive countless tools. Looking up [section] key=value teaches stateful line parsing.

Input format

ini: config text. section/key: lookup target. out/cap: result buffer and size.

Output format

int length of the value copied to out, or -1 if not found / overflow / NULL.

Constraints

Stateful: track [section]; match keys exactly, only within the right section.

Starter code

#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;
}

Common mistakes

Matching a key in the wrong section. Prefix-matching keys (use exact length). Forgetting the overflow guard.

Edge cases to handle

Same key in two sections. Missing key. Section with no such key.

Complexity

O(text length).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.