当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C++ getenv()用法及代码示例

C++ getenv() 函数

getenv() 函数是 cstdlib 头文件的库函数。它用于获取环境字符串。它接受一个作为环境变量名称的参数(取决于平台,可能区分大小写或不区分大小写)并返回一个 C-string,其中包含指定为参数的环境变量的值。

注意:该函数是平台相关的,如果未定义指定参数(环境变量),则返回空指针。

getenv() 函数的语法:

C++11:

    char* getenv (const char* name);

参数:

  • name– 表示环境变量的名称。

返回值:

这个函数的返回类型是char*,它返回一个 C-string,其中包含指定为参数的环境变量的值。

例:

    Function call:
    getenv ("PATH");

    Output:
    Specified the environment variable (PATH)

C++代码演示getenv()函数的例子

// C++ code to demonstrate the example of
// getenv() function

#include <iostream>
#include <cstdlib>
using namespace std;

// main() section
int main()
{
    char* path_string;
    
    // getting path
    path_string = getenv ("PATH");
    
    if (path_string!=NULL)
    cout<<"The current path is:"<<path_string<<endl;

    return 0;
}

输出

RUN 1:(Compiler:https://www.onlinegdb.com/ (c++))
The current path is:/opt/swift/swift-5.0-RELEASE-ubuntu14.04/usr/bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

RUN 2:(Compiler:https://www.jdoodle.com/online-compiler-c++/)
The current path is:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/isCOBOL2019R1/bin:/opt/cs/artifacts/Release/bin

参考:C++ getenv() 函数



相关用法


注:本文由纯净天空筛选整理自 getenv() Function with Example in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。