Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to print environment variables
In C programming, environment variables are global system variables that contain information about the operating system and user environment. These variables can affect how running processes behave on the system. C provides access to environment variables through the third parameter of the main() function.
Syntax
int main(int argc, char *argv[], char *envp[])
Parameters:
-
argc− Number of command-line arguments -
argv[]− Array of command-line argument strings -
envp[]− Array of environment variable strings (NULL-terminated)
Example: Print All Environment Variables
This program iterates through the envp array to print all environment variables −
#include <stdio.h>
int main(int argc, char *argv[], char *envp[]) {
int i;
printf("Environment Variables:<br>");
printf("=====================<br>");
for (i = 0; envp[i] != NULL; i++) {
printf("%s<br>", envp[i]);
}
printf("\nTotal environment variables: %d<br>", i);
return 0;
}
Environment Variables: ===================== ALLUSERSPROFILE=C:\ProgramData CommonProgramFiles=C:\Program Files\Common Files HOMEDRIVE=C: NUMBER_OF_PROCESSORS=2 OS=Windows_NT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC PROCESSOR_ARCHITECTURE=x86 PROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=2a07 ProgramData=C:\ProgramData ProgramFiles=C:\Program Files PUBLIC=C:\Users\Public SESSIONNAME=Console SystemDrive=C: SystemRoot=C:\Windows windir=C:\Windows Total environment variables: 17
Alternative Method: Using extern char **environ
Another way to access environment variables is using the global environ variable −
#include <stdio.h>
extern char **environ;
int main() {
int i = 0;
printf("Environment Variables (using extern environ):<br>");
printf("=============================================<br>");
while (environ[i] != NULL) {
printf("%s<br>", environ[i]);
i++;
}
return 0;
}
Key Points
- Environment variables are stored as name=value pairs
- The
envparray is NULL-terminated likeargv - Environment variables are inherited from the parent process
- Common variables include PATH, HOME, USER, and system-specific variables
Conclusion
C programs can access environment variables through the envp parameter or the global environ variable. This allows programs to adapt their behavior based on system configuration and user preferences.
Advertisements
