Linux C中environ 变量是一个char** 类型,存储着系统的环境变量。
要想遍历环境变量可以用下面这个程序:
#include <stdio.h> extern char ** environ; int main() { char ** envir = environ; while(*envir) { fprintf(stdout,"%s ",*envir); envir++; } return 0; }
因为environ是一个全局的外部变量,所以切记使用前要用extern关键字进行声明,然后在使用。
unistd.h头文件中声明了这个变量,所以也可以将unist.h进行include,这个时候就不用再对environ进行extern声明了(应为unistd.h中已经声明了),代码如下:
#include <stdio.h> #define __USE_GNU #include <unistd.h> //extern char ** environ; int main() { char ** envir = environ; while(*envir) { fprintf(stdout,"%s ",*envir); envir++; } return 0; }
要注意的问题是,在unistd.h中声明environ的地方使用了条件编译,编译的条件就是#ifdef __USE_GNU,LinuxC中默认没有定义这个宏,所以要在#include <unistd.h>之前加上#define __USE_GNU
还有一种方法遍历环境变量,就是利用main函数的参数,我们常见的main函数带有两个参数int argc 和 char * argv[], 但实际上还有一个带有三个参数的main函数,如下:
int main(int argc, char *argv[], char *env[]) { int index = 0; while(env[index] != NULL) { printf("env[%d]: %s ", index, env[index]); ++index; } return 0; }
就写到这里了,希望对大家有帮助。。不对之处还请指教,,谢谢~~