JIYIK CN >

Current Location:Home > Learning > PROGRAM > C语言 >

Use the C language setenv function to access environment variables

Author:JIYIK Last Updated:2025/04/17 Views:

setenvThis article will introduce several methods of using functions to export environment variables in C language .


setenvUse function to export environment variables in C language

Every program running on a Unix-base system has an environment, which is a collection of variable-value pairs used primarily by the shell and other user-space programs. A program can getenvretrieve a single environment variable and its value with the _environment_variable function. But if you want to define a new variable or change an existing one, you should call the _environment_variable setenvfunction. It takes three arguments, the first and second arguments are charpointers to the variable name and its value, respectively. The third argument is of type _environment_variable int, which specifies whether the value of the given variable should be overwritten if it already exists in the environment. A non-zero value for this parameter indicates overwriting behavior, while a zero value indicates the opposite.

But please note that to iterate over all defined environment variables, you need to access environa special global variable named -, which is a NULL-terminated string array. Alternatively, you can declare maina function with a third parameter envpto access the variable. In the following example, we print both the and pointers setenvbefore and after calling the function . Note that after the call, the value of the pointer is the same, while the value of has changed.enironenvpenvpenviron

#include <stdio.h>
#include <stdlib.h>

extern char **environ;

int main(int argc, const char *argv[], const char *envp[]) {

    printf("environ:  %p\n", environ);
    printf("envp:     %p\n", envp);

    setenv("NEW_VAR", "new_value", 1);

    puts("----Added NEW_VAR----");
    printf("environ:  %p\n", environ);
    printf("envp:     %p\n", envp);

    exit(EXIT_SUCCESS);
}

Output:

environ:  0x7fffa05a7fe8
envp:     0x7fffa05a7fe8
----Added NEW_VAR----
environ:  0x5646431276b0
envp:     0x7fffa05a7fe8

Use envpvariables to iterate over defined environment variables in C

The previous code example illustrates why you should avoid setenvusing mainthe function parameter envpto retrieve environment variables after calling the function. When setenvthe function is called, the environment is relocated, but envpstill points to the old environment. The following sample code demonstrates the incorrect behavior by setenvdefining a new variable with the call and then iterating over the array of pointers. Note that we also use the statement to jump to the end of the loop envpif NEW_VARa variable named is found.goto

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *argv[], const char *envp[]) {

    if (setenv("NEW_VAR", "new_value", 1) != 0) {
        perror("setenv");
        exit(EXIT_FAILURE);
    }

    if (envp != NULL) {
        for (size_t i = 0; envp[i] != NULL; ++i) {
            if (strcmp(envp[i], "NEW_VAR=new_value") == 0) {
                puts(envp[i]);
                goto END;
            }
        }
        printf("No such variable found!\n");
    } END:

    exit(EXIT_SUCCESS);
}

Output:

No such variable found!

Use environvariables to iterate over defined environment variables in C

Since the previous solution cannot find the newly defined variables, we should use externally declared environvariables. In this case, we have included multiple preprocessor conditional statements to make the code portable across different systems, but it is only needed in most UNIX-based systems extern char **environ. Once declared, we can use the same loop we implemented in the previous example to iterate over the list of variables.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined (_POSIX_) || defined (__USE_POSIX)
extern char **environ;
#elif defined(_WIN32)
_CRTIMP extern char **_environ;
#endif

int main(void) {

    if (setenv("NEW_VAR", "new_value", 1) != 0) {
        perror("setenv");
        exit(EXIT_FAILURE);
    }

    if (environ != NULL) {
        for (size_t i = 0; environ[i] != NULL; ++i) {
            if (strcmp(environ[i], "NEW_VAR=new_value") == 0) {
                puts(environ[i]);
                goto END;
            }
        }
        printf("No such variable found!\n");
    } END:

    exit(EXIT_SUCCESS);
}

Output:

NEW_VAR=new_value

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Flushing stdout output stream in C

Publish Date:2025/04/17 Views:200 Category:C语言

stdout This article will demonstrate various methods on how to flush an output stream in C language . Use function in C language fflush to refresh stdout output stream I/O The C standard library provides a stdio buffered version of the I/O

Using the feof function in C language

Publish Date:2025/04/17 Views:87 Category:C语言

feof This article will introduce several ways to use functions in C language . Use feof the function to check the end-of-file indicator on a file stream in C language feof The function is part of the C standard input/output library and is d

在C中将整数转换为字符

Publish Date:2024/01/03 Views:135 Category:C语言

本教程介绍了在C中将整数转换为字符的不同方法。在C编程语言中,将整数转换为字符在各种情况下都很重要。在C中,字符是以ASCII值表示的,因此转换过程相对简单。

在 C 语言中使用 typedef enum

Publish Date:2023/05/07 Views:372 Category:C语言

本文介绍了如何在 C 语言中使用 typedef enum。使用 enum 在 C 语言中定义命名整数常量 enum 关键字定义了一种叫做枚举的特殊类型。

C 语言中的静态变量

Publish Date:2023/05/07 Views:170 Category:C语言

本文介绍了如何在 C 语言中使用静态变量。在 C 语言中使用 static 变量在函数调用之间保存变量值

C 语言中生成随机数

Publish Date:2023/05/07 Views:159 Category:C语言

本文演示了如何在 C 语言中生成随机数。使用 rand 和 srand 函数在 C 语言中生成随机数

C 语言中的 i++ 与++i

Publish Date:2023/05/07 Views:130 Category:C语言

本文演示了如何在 C 语言中使用前缀增量与后缀增量运算符。C 语言中++i 和 i++ 记号的主要区别

C 语言中获取当前工作目录

Publish Date:2023/05/07 Views:280 Category:C语言

本文演示了如何在 C 语言中获取当前工作目录。使用 getcwd 函数获取当前工作目录的方法

C 语言中的位掩码

Publish Date:2023/05/07 Views:178 Category:C语言

本文介绍了如何在 C 语言中使用位掩码。使用 struct 关键字在 C 语言中定义位掩码数据

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial