简体   繁体   English

如何编写自己的setenv()?

[英]How do I program my own setenv()?

My school wants me to implement the setenv() standard library function's behavior. 我的学校要我实现setenv()标准库函数的行为。 I'm not allowed to use setenv() for this implementation. 我不允许在这个实现中使用setenv() How can I do that? 我怎样才能做到这一点?

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: 例如,如果您的环境具有变量foobarbaz ,则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.

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