file-handling · intermediate · ~15 min

Read a value from INI text

Stateful line-by-line config parsing.

Challenge

Your job

int ini_get(const char *ini, const char *section, const char *key, char *out, size_t cap);

ini is newline-separated config text with [section] headers and key=value lines. Return the value for key inside section in out, or -1 if not found / overflow / NULL.

Hints

  1. Track the current section as you see [name] lines.
  2. Only match key= when you're inside the requested section.
  3. Copy everything after the = into out.

Why this matters

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

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.