basics · beginner · ~15 min
Walk argv defensively and parse a `key=value` syntax.
Scan a program's command-line arguments for a --key=value flag and hand back the value — a hand-rolled mini version of getopt_long.
Implement int find_flag(int argc, char **argv, const char *key, const char **out). Scan argv[1] through argv[argc-1] for the first argument that begins with key immediately followed by =. If found, set *out to point at the value (everything after the =, which may be empty) and return 1. If no such argument exists, return 0 and leave *out unchanged.
argc/argv as passed to main, a flag name key such as "--port", and an output pointer out that receives the value on success.
Returns 1 if the flag is present (with *out pointing into argv at the value), otherwise 0.
argv = {"prog", "--port=8080", "--debug"}
find_flag(3, argv, "--port", &out) -> 1, *out == "8080"
find_flag(3, argv, "--foo", &out) -> 0
argv = {"prog", "--port="}
find_flag(2, argv, "--port", &out) -> 1, *out == "" (empty value)
key but with no = (e.g. "--port" alone) does not match.= is a valid match.*out points into argv (valid for the program's lifetime).strncmp), not strcmp, and verify the = separator.Almost every CLI tool you'll write or audit takes flags. Doing a tiny parser by hand teaches you exactly what getopt_long does for free.
argc/argv as passed to main, a key string, and an out pointer for the value.
1 if the flag is found (with *out set to the value), otherwise 0.
No allocations; *out is a pointer into argv. Match key followed by '='; take the first match.
int find_flag(int argc, char **argv, const char *key, const char **out) { /* TODO */ return 0; }
Using strcmp to test prefix — only matches the whole arg. Use strncmp with key length, then verify = follows.
No matching flag; argv[i] equal to key without =; multiple matches (take first).
O(argc * keylen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.