Print the environment variables using environ

21,220

Solution 1

#include <unistd.h>
#include <stdio.h>

extern char **environ;
//...

int i = 0;
while(environ[i]) {
  printf("%s\n", environ[i++]); // prints in form of "variable=value"
}

Solution 2

Do you mean

int main(int argc, char **argv, char **envp)
{
    while(*envp!=null) {
        printf("%s\n", *envp);
        envp++;
    }
    return 0;
}
Share:
21,220
nitin_cherian
Author by

nitin_cherian

nitin_cherian: Sneior Lead Engineer at ADVA Optical Networking, Bangalore, India Languages worked on: C, C++, Python Operating systems worked on: Linux Current Interests: Python Language, Game development in Python. Crafting Quality code in Python. Online Courses: Cryptography1, Interactive Programming in Python @ www.coursera.com. Hobbies: Reading short articles in newspaper and magazines.

Updated on July 09, 2022

Comments

  • nitin_cherian
    nitin_cherian almost 2 years

    How to print the environment variables in a C program using "environ".

    extern char **environ

  • nitin_cherian
    nitin_cherian over 13 years
    exactly what i needed? So environ is actually an array of character pointers right? and each character pointer in the array points to an environment variable right??
  • sje397
    sje397 over 13 years
    Each pointer points to a string (yeah, char array) of the form "variable=value". The last entry is a null-pointer, which ends the loop above.
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 13 years
    You forgot extern char **environ;. While some nonstandard systems may declare it in a header file, POSIX specifies that it is not available unless you declare it yourself manually.
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 13 years
    No, extern char **environ; is POSIX standard. This signature for main is completely nonstandard.
  • jim mcnamara
    jim mcnamara over 13 years
    You are completely correct. However. That was why I asked. It compiles and runs correctly under gcc on Solaris 9 & 10, under cc on HPUX 10i, 11.0, and 11i. It also compiled and ran on older versions of DEC Unix and DGUX. The point being that people get **environ and the old int main( int, char **, char *) confused. I don't have my K&R around to verify or I would claim it in there as well. What does your K&R say?