/* * program to print environment variables * invocation: * prenv print argument list * prenv arg1 ... print value of argument(s) * exit code: number of environment variables not found * author: Matt Bishop, bishop@cs.ucdavis.edu, 9/16/96 */ #include <stdlib.h> #include <string.h> #include <stdio.h> int main(int argc, char *argv[], char *envp[]) { register int i; /* counter in for loops */ register int narg; /* number of current argument */ register int len; /* length of current argument */ register int found; /* 1 if env. variable found */ register int exstat = 0; /* exit status code */ /* * no arguments; just print the environment * variables and their values */ if (argc == 1){ /* just loop and print */ for(i = 0; envp[i] != NULL; i++) printf("%s\n", envp[i]); /* all done! */ return(EXIT_SUCCESS); } /* * arguments given; just print the values * associated with these named variables */ for(narg = 1; argv[narg] != NULL; narg++){ /* just an optimization ... */ len = strlen(argv[narg]); /* assume no such variable */ found = 0; /* * now look for the variable */ for(i = 0; envp[i] != NULL; i++) /* see if this one is it*/ if (strncmp(envp[i], argv[narg], len) == 0){ /* name= means value follows = */ if (envp[i][len] == '='){ printf("%s\n", envp[i] + len + 1); found++; } /* name means value is empty */ /* anything else, it doesn't match */ else if (!envp[i][len]){ putchar('\n'); found++; } } /* * did we find it? */ if (!found){ /* nope -- print error message */ fprintf(stderr, "%s: no such variable\n", argv[narg]); /* one more unknown environment variable */ exstat++; } } /* * return number of unknown environment variables */ return(exstat); }
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |