如何列出 c/c++ 应用程序中的所有环境变量

2023-08-26C/C++开发问题
3

本文介绍了如何列出 c/c++ 应用程序中的所有环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道在用 C++ 编程时,我可以使用 getenv<访问各个环境变量/code>.

I know that when programming in c++ I can access individual environment variables with getenv.

我也知道,在 os x 终端中,我可以使用 <列出所有当前的环境变量代码>环境.

I also know that, in the os x terminal, I can list ALL of the current environment variables using env.

我有兴趣获得可用于我正在运行的 C++ 程序的环境变量的完整列表.是否有一个 c/c++ 函数可以列出它们?换句话说,有没有办法从我的 C++ 代码中调用 env ?

I'm interested in getting a complete list of the environment variables that are available to my running c++ program. Is there a c/c++ function that will list them? In other words, is there a way to call env from my c++ code?

推荐答案

使用 environ 全局变量.它是一个空终止指针,指向格式为 name=value 的字符串数组.这是 env 的一个微型克隆:

Use the environ global variable. It is a null-terminated pointer to an array of strings in the format name=value. Here's a miniature clone of env:

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

extern char **environ;

int main(int argc, char **argv) {
    for(char **current = environ; *current; current++) {
        puts(*current);
    }
    return EXIT_SUCCESS;
}

这篇关于如何列出 c/c++ 应用程序中的所有环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6