In: Computer Science
Please complete the following code in C using the comments as instructions. Further instructions are below the code.
challenge.c
// goal: print the environment variables to the file "env.txt", one per line
// (If envp is NULL, the file should be empty, opening in write mode will do that.)
// example:
// inputs:
// envp/environ = {"E1=2","E2=7",NULL}
// outputs:
// env.txt as a string would be "E1=2\nE2=7\n"
// example:
// inputs:
// envp/environ = {NULL} or NULL
// outputs:
// env.txt as a string would be ""
//
// TODO: write and complete the main function
int main()
{
return 0;
}
---
INSTRUCTIONS.txt
You are given a file, challenge.c.
You may edit this file as you wish.
All the work you need to do is in challenge.c.
You are making an entire program in challenge.c (so a main function needs to be in there)
All this program does is print the environment variables to a file called "env.txt"
Each variable is followed by a newline character
example:
inputs:
envp/environ = {"E1=2","E2=7",NULL}
outputs:
env.txt as a string would be "E1=2\nE2=7\n"
example:
inputs:
envp/environ = {NULL} or NULL
outputs:
env.txt as a string would be ""
#include <stdio.h>
extern char **environ;
int main(void)
{
int i;
FILE * fp;
fp = fopen ("env.txt","w");
for (i = 0; environ[i] != NULL; i++){
if(environ[i]==NULL){
fp = fopen ("env.txt","w");
fprintf (fp, "");
}
fprintf (fp, "%s\n",environ[i]);
}
fclose (fp);
return 0;
}
you can also get at the environment via environ
,
even in functions other than main()
. The variable
environ
is unique amongst the global variables defined
by POSIX ans is not declared in any header file, so you must write
the declaration yourself.
extern char **environ
means
the list of environments.