How to get environment variables in C in a cross platform way

依然范特西╮ 提交于 2019-12-07 04:23:19

问题


I'm using the following code in OSX and in 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).

I define the same ENV variables in both OS in Russian language: MY_ENV='russian letters goes here'. And have got a difference about 2 times in a length of a strings.

This length I'm planning to use in malloc and want them be the same. How can I get the same lengths correctly, in CRT way?


回答1:


  • getenv is available on GNU/Linux, Mac OS X, and Microsoft Windows.
  • setenv is available of GNU/Linux and Mac OS X but not on Microsoft Windows.
  • putenv, like getenv, is available on GNU/Linux, Mac OS X, and Microsoft Windows.

Thus getenv and putenv are your best cross-platform options.



来源:https://stackoverflow.com/questions/21557479/how-to-get-environment-variables-in-c-in-a-cross-platform-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!