我如何编程自己的setenv()? [英] How do I program my own setenv()?
问题描述
我的学校希望我实施 setenv()
标准 c 库函数的行为.我不允许为此实现使用 setenv()
.我该怎么办?
My school wants me to implement the setenv()
standard c library function's behavior. I'm not allowed to use setenv()
for this implementation. How can I do that?
推荐答案
在C编程语言的许多实现中,尤其是在POSIX上,可以从 environ
全局变量访问环境.您可能需要手动声明它,因为它没有在任何标准头文件中声明:
On many implementations of the C programming language and especially on POSIX, the environment is accessible from the environ
global variable. You may need to declare it manually as it's not declared in any standard header file:
extern char **environ;
environ
指向以 variable = value
字符串为指针的,以 NULL
终止的指针数组.例如,如果您的环境具有变量 foo
, bar
和 baz
,则 environ
中的条目可能是:
environ
points to a NULL
terminated array of pointers to variable=value
strings. For example, if your environment has the variables foo
, bar
, and baz
, the entries in environ
might be:
environ[0] = "foo=a";
environ[1] = "bar=b";
environ[2] = "baz=c";
environ[3] = NULL;
要更改环境而不使用 setenv()
或 putenv()
函数,请检查要设置的密钥是否已存在.如果是这样,则覆盖该密钥的条目.否则,您需要将 environ
的内容复制到新数组中,并将新条目添加到其末尾.为此,您可以使用 malloc()
或 calloc()
和 memcpy()
.由于这是家庭作业,因此我将不提供更多详细信息.
To alter the environment without using the setenv()
or putenv()
functions, check if the key you want to set already exists. 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. You can use malloc()
or calloc()
and memcpy()
for this purpose. Since this is homework, I'm not going to supply further details.
这篇关于我如何编程自己的setenv()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!