linux-sysprog · intermediate · ~15 min
Walk the process environment.
Count how many environment variables have a name beginning with a given prefix.
Implement int env_count_with_prefix(const char *prefix) that returns the number of entries in the process environment whose name starts with prefix.
prefix: a NUL-terminated string. The process environment is the global environ array — a NULL-terminated array of "NAME=value" strings.Returns the count of environ entries that start with prefix (a plain prefix match against the whole "NAME=value" string).
env CPLAT_X=1 CPLAT_Y=2 CPLAT_Z=3
env_count_with_prefix("CPLAT_") -> 3
env_count_with_prefix("__NONEXIST_") -> 0
A NUL-terminated prefix string. The process environment is the global environ array of 'NAME=value' strings.
The number of environ entries whose text starts with prefix, as an int.
Walk environ until its NULL terminator; compare with strncmp. NULL prefix returns 0.
#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.