linux-sysprog · intermediate · ~15 min

Count env vars with prefix

Walk the process environment.

Challenge

Count how many environment variables have a name beginning with a given prefix.

Task

Implement int env_count_with_prefix(const char *prefix) that returns the number of entries in the process environment whose name starts with prefix.

Input

  • prefix: a NUL-terminated string. The process environment is the global environ array — a NULL-terminated array of "NAME=value" strings.

Output

Returns the count of environ entries that start with prefix (a plain prefix match against the whole "NAME=value" string).

Example

env CPLAT_X=1 CPLAT_Y=2 CPLAT_Z=3
env_count_with_prefix("CPLAT_")       ->   3
env_count_with_prefix("__NONEXIST_")  ->   0

Edge cases

  • A prefix that matches nothing returns 0.
  • A NULL prefix returns 0.

Input format

A NUL-terminated prefix string. The process environment is the global environ array of 'NAME=value' strings.

Output format

The number of environ entries whose text starts with prefix, as an int.

Constraints

Walk environ until its NULL terminator; compare with strncmp. NULL prefix returns 0.

Starter code

#include <unistd.h>
#include <string.h>
extern char **environ;
int env_count_with_prefix(const char *prefix) {
    /* TODO */
    return 0;
}

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