C C++ 环境变量获取\设置\倾印

#include <iostream>

#include "stdlib.h"

#pragma warning(disable:4996)

class Env
{
public:
    //sample: char * libvar = getenv( "LIB" ); // C4996
    //Return 0 if successful or -1 in the case of an error.
    static int put(const char *envstring)
    {
        return _putenv(envstring);
    }

    static int put(const wchar_t *envstring)
    {
        return _wputenv(envstring);
    }

    //sample: _putenv( "LIB=c:\\mylib;c:\\yourlib" ); // C4996
    //return value is NULL if varname is not found in the environment table
    static char *get(const char *varname)
    {
        return getenv(varname);
    }

    static wchar_t *get(const wchar_t *varname)
    {
        return _wgetenv(varname);
    }


    static wchar_t ** table()
    {
        return _wenviron;//In a program that uses main, _wenviron is initially NULL
    }


    static char ** table_narrow()
    {
        return _environ;//in a program that uses wmain, _environ is initially NULL 
    }
};

using namespace std;
//简单测试
int wmain()
{
    wchar_t * libvar = Env::get(L"path");

    if(libvar)
        wcout << libvar <<L"\n\n"<< endl;

    //附加 C:\\Dir 到 %path% 末尾
    wstring pathenv = wstring(L"path=") + wstring(libvar) + L";" + L"C:\\Dir;";

    Env::put(pathenv.c_str());

    //列出所有环境变量
    wchar_t ** estrp = Env::table();
    if (estrp)
    {
        while (*estrp)
        {
            wcout << *estrp << endl;
            estrp++;
        }
    }


    //char ** estrp2 = Env::table_narrow();
    //if (estrp2)
    //{
    //    while (*estrp2)
    //    {
    //        cout << *estrp2 << endl;
    //        estrp2++;
    //    }
    //}

}


//int main()
//{
//    std::cout << "Hello World!\n";
//
//    wchar_t ** estrp = Env::table();  //return Null
//    if (estrp)
//    {
//        while (*estrp)
//        {
//            std::wcout << *estrp << std::endl;
//            estrp++;
//        }
//    }
//
//
//    char ** estrp2 = Env::table_narrow();
//    if (estrp2)
//    {
//        while (*estrp2)
//        {
//            std::cout << *estrp2 << std::endl;
//            estrp2++;
//        }
//    }
//
//}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值