How do I program my own setenv()?
Asked Answered
C

1

1

My school wants me to implement the setenv() standard library function's behavior. I'm not allowed to use setenv() for this implementation. How can I do that?

Catherine answered 15/12, 2015 at 22:20 Comment(5)
What's wrong with setenv?Hermes
It's in stdlib, should work, no?Dric
I can't use setenv my school forbit using itCatherine
My school wants I create the setenv functionCatherine
@Catherine Maybe you should clarify your question to indicate that.Hermes
A
4

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 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;

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.

Avelin answered 15/12, 2015 at 22:31 Comment(4)
Thanks a lot for this solutionCatherine
@FUZxxl I realized that this was the solution, but I also suspected that you would write it.Differentiate
@Catherine This is the acceptable answer because it's correct. Whether you try it and it works or not, depends on your skills with malloc() and memcpy(). Not that you can end up corrupting the environ buffer.Differentiate
@FUZxxl: adding a new string at the end will not always produce the expected behavior, the OP should first scan the strings to find a potential match for the environment variable whose value needs to be set and not copy this line into the new environment array.Wack

© 2022 - 2024 — McMap. All rights reserved.