wiki:Programming/C/ExamplePrintArgsAndEnv

Example Print Args and Env

This is a simple example of using GCC to print the arguments and environment when a C program is called:

echo -e "#include <stdio.h>\n int main(int argc, char **argv, char **env) \
 {\n printf(\"Hello from %s\", argv[0]);\n for (int i=1; i<argc; i++) {\n \
 printf(\" %s,\", argv[i]); }\n printf(\"\\\n\");\n \
 {\n char **envp = env; while (*envp != 0) {\n printf(\"%s\\\n\", *envp);\n envp++; \
 }\n }\n return 0;\n}" | gcc -o helloworld -std=c99 -x c -

./helloworld this is a test

The program code in an easy-read format:

#include <stdio.h>
int main(int argc, char **argv, char **env) {
 printf("Hello from %s", argv[0]);
 for (int i=1; i<argc; i++) {
  printf(" %s,", argv[i]);
 }
 printf("\n");
 {
  char **envp = env;
  while (*envp != 0) {
   printf("%s\n", *envp);
   envp++;
  }
 }
 return 0;
}