代码以及一些注意事项。

代码实验:

getenv()

1
2
#include <stdlib.h>
char *getenv(const char *name);

The getenv() function searches the environment list to find the environment variable name, and returns a pointer to the corresponding value string. The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>

int main() {
// 获取一个不存在的环境变量
const char* name = "ABCD";
char* ret_val = getenv(name);
printf("%s = %s\n", name, ret_val); // 直接 %s 输出 null 是输出的 (null)

// 获取一个存在的环境变量
const char* path = "PATH";
char* path_val = getenv(path);
printf("%s = %s\n", path, path_val);

return 0;
}

getenv输出

setenv() & putenv()

setenv()

1
2
3
4
5
#include <stdlib.h>
int setenv(const char *name, const char *value, int overwrite);

#include <stdlib.h>
int putenv(char *string);

The setenv() function adds the variable name to the environment with the value value, if name does not already exist. If name does exist in the environment, then its value is changed to value if overwrite is nonzero; if overwrite is zero, then the value of name is not changed. This function makes copies of the strings pointed to by name and value (by contrast with putenv(3)).

The setenv() function returns zero on success, or -1 on error, with errno set to indicate the cause of the error.

注意一哈哈:如果这个环境变量已经存在了,overwrite传非0值,会覆盖原有的环境变量。传0则不会覆盖。

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <stdlib.h>

int main() {
// 设置一个不存在的环境变量
const char* name = "ABCD";
setenv(name, "aaa-bbb-ccc-ddd", 1);
char* ret_val = getenv(name);
printf("%s = %s\n", name, ret_val);

return 0;
}

输出及测试

putenv()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <stdlib.h>

int main()
{
setenv("ABCD", "aaa-bbb-ccc-ddd", 0);
printf("%s = %s\n", "ABCD", getenv("ABCD"));

char abcd[1024] = "ABCD=abcd"; // 注意这里如果是 const char * 会有警告,因为参数要的是char *
int ret = putenv(abcd);
printf("ret = %d\n", ret);
printf("%s = %s\n", "ABCD", getenv("ABCD"));

return 0;
}

输出

注意

运行env.out程序后设置的环境变量是给这个程序设置的环境变量。emmm,没描述清楚,我想想怎么表达。

env.out执行setenv设置的环境变量,只有在它的那个进程中可用。

unsetenv()

1
2
#include <stdlib.h>
int unsetenv(const char *name);

The unsetenv() function deletes the variable name from the environment. If name does not exist in the environment, then the function succeeds, and the environment is unchanged. The unsetenv() function returns zero on success, or -1 on error, with errno set to indicate the cause of the error.

如果要删除的环境变量不存在,返回的是0。也就是说你没有这个环境变量他也会帮你抹除,如果传入的参数是有误的(比如传入”ABCD=”),则会返回错误(-1)。

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <stdlib.h>

int main() {
setenv("ABCD", "aaa-bbb-ccc-ddd", 0);
printf("%s = %s\n", "ABCD", getenv("ABCD"));

int ret = unsetenv("ABCD");
printf("ret = %d\n", ret);

return 0;
}

ret = 0

将unsetenv的参数修改为:"ABC="

ret = -1