[英]How do I program my own setenv()?
On many implementations of the C programming language and especially on POSIX, the environment is accessible from the environ
global variable. 在C编程语言的许多实现上,特别是在POSIX上,可以从
environ
全局变量访问该environ
。 You may need to declare it manually as it's not declared in any standard header file: 您可能需要手动声明它,因为它未在任何标准头文件中声明:
extern char **environ;
environ
points to a NULL
terminated array of pointers to variable=value
strings. environ
指向以NULL
结尾的指向variable=value
字符串的指针数组。 For example, if your environment has the variables foo
, bar
, and baz
, the entries in environ
might be: 例如,如果您的环境具有变量
foo
, bar
和baz
,则environ
的条目可能是:
environ[0] = "foo=a";
environ[1] = "bar=b";
environ[2] = "baz=c";
environ[3] = NULL;
To alter the environment without using the setenv()
or putenv()
functions, check if the key you want to set already exists. 要在不使用
setenv()
或putenv()
函数的情况下更改环境,请检查要设置的键是否已存在。 If it does, overwrite the entry for that key. 如果是,则覆盖该密钥的条目。 Else you need to copy the content of
environ
into a new array and add the new entry to its end. 否则,您需要将
environ
的内容复制到新数组中,并将新条目添加到其末尾。 You can use malloc()
or calloc()
and memcpy()
for this purpose. 您可以使用
malloc()
或calloc()
和memcpy()
来实现此目的。 Since this is homework, I'm not going to supply further details. 由于这是家庭作业,我不打算提供更多细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.