简体   繁体   English

如何以跨平台方式在C中获取环境变量

[英]How to get environment variables in C in a cross platform way

I'm using the following code in OSX and in Windows Vista: 我在OSX和Windows Vista中使用以下代码:

#include <stdio.h>
#include <string.h>

extern char **environ;

int
main(int argc, char **argv)
{
    int i;
    for (i = 0; environ[i] != NULL; i++)
    {
        printf("var = %s - %d\n", environ[i], (int)strlen(environ[i]));
    }

    return 0;
}

On OSX compile it with cc , on Windows - with 'cl' from Windows SDK 7.1 (with Redistributable Packages: Microsoft Visual C++ 2010 in it). 在OSX上,使用cc编译,在Windows上-使用Windows SDK 7.1的“ cl”进行编译(可重新发行软件包:Microsoft Visual C ++ 2010)。

I define the same ENV variables in both OS in Russian language: MY_ENV='russian letters goes here'. 我在两个操作系统中都用俄语定义了相同的ENV变量:MY_ENV =“俄语字母在这里”。 And have got a difference about 2 times in a length of a strings. 弦长相差约2倍。

This length I'm planning to use in malloc and want them be the same. 我打算在malloc使用此长度,并希望它们相同。 How can I get the same lengths correctly, in CRT way? 如何以CRT方式正确获得相同的长度?

  • getenv is available on GNU/Linux, Mac OS X, and Microsoft Windows. getenv在GNU / Linux,Mac OS X和Microsoft Windows上可用。
  • setenv is available of GNU/Linux and Mac OS X but not on Microsoft Windows. setenv在GNU / Linux和Mac OS X上可用,但在Microsoft Windows上不可用。
  • putenv , like getenv , is available on GNU/Linux, Mac OS X, and Microsoft Windows. putenv ,像getenv ,可在GNU / Linux和Mac OS X和微软的Windows。

Thus getenv and putenv are your best cross-platform options. 因此, getenvputenv是您最好的跨平台选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM