In: Computer Science
Write a C program which prints the environment variables to a file "sample.txt" . All variables are followed by a newline character. example: example: inputs: envp/environ = {"E1=5","E2=9",NULL} outputs: env.txt as a string would be "E1=5\nE2=9\n".
This is the version that should work on old environments.
#include <stdio.h>
int main(int argc, char **argv, char **envp)
{
int i = 0;
FILE *fp;
fp = fopen("sample.txt", "w");
if (fp == NULL)
{
perror("File Not found");
return -1;
}
while(envp[i])
{
fprintf(fp, "%s\n", envp[i]);
i++;
}
fclose(fp);
return 0;
}
=======================
In old times there was third option to main argument that would
point to list of all the environment variables just like argv
points to list of command line arguments.
int main(int argc, char **argv, char **envp);
But that option is not portable in some posix systems, and works
in unix like system. A better approach is to use
char **environ defined in unistd.h which holds the same list of
environment variable.
Below is the program to read this variable one by one and print the variable with values to sample.txt file.
#include <stdio.h>
#include <unistd.h>
int main()
{
int i = 0;
FILE *fp;
fp = fopen("sample.txt", "w");
if (fp == NULL)
{
perror("File Not found");
return -1;
}
while(environ[i])
{
fprintf(fp, "%s\n", environ[i]);
i++;
}
fclose(fp);
return 0;
}
Compilation: gcc <filename.c>
Few lines of text from sample.txt file
OS=Windows_NT
COMMONPROGRAMFILES=C:\Program Files (x86)\Common Files
PROCESSOR_LEVEL=6
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program
Files (x86)\AutoIt3\AutoItX
PROCESSOR_ARCHITEW6432=AMD64
CUDA_PATH_V10_2=D:\Program Files\NVIDIA GPU
Toolkit\CUDA\v10.2