C++系統相關操作2 - 獲取系統環境變數

陌尘(MoChen)發表於2024-06-21
  • 1. 關鍵詞
  • 2. sysutil.h
  • 3. sysutil.cpp
  • 4. 測試程式碼
  • 5. 執行結果
  • 6. 原始碼地址

1. 關鍵詞

C++ 系統呼叫 環境變數 getenv 跨平臺

2. sysutil.h

#pragma once

#include <cstdint>
#include <string>

namespace cutl
{
    /**
     * @brief Get an environment variable.
     *
     * @param name the name of the environment variable.
     * @param default_value the default value if the variable is not found.
     * @return std::string the value of the environment variable.
     */
    std::string getenv(const std::string &name, const std::string &default_value);
} // namespace cutl

3. sysutil.cpp


#include <map>
#include <iostream>
#include <strutil.h>
#include <cstdlib>
#include "sysutil.h"
#include "inner/logger.h"
#include "inner/system_util.h"
#include "inner/filesystem.h"

namespace cutl
{
    std::string getenv(const std::string &name, const std::string &default_value)
    {
        const char *text = std::getenv(name.c_str());
        if (text == nullptr)
        {
            CUTL_ERROR("variable [" + name + "] not set, fallback to " + default_value);
            return default_value;
        }

        return std::string(text);
    }
} // namespace cutl

4. 測試程式碼

#include "common.hpp"
#include "sysutil.h"

void TestGetEnv()
{
    PrintSubTitle("TestGetEnv");

    auto result = cutl::getenv("PATH", "not found");
    std::cout << "getenv for PATH, result:" << std::endl
              << result << std::endl;

    // for Windows testing
    std::cout << "USERPROFILE: " << cutl::getenv("USERPROFILE", "not found") << std::endl;
    std::cout << "PROCESSOR_ARCHITECTURE: " << cutl::getenv("PROCESSOR_ARCHITECTURE", "not found") << std::endl;
    // FOR UNIX/LINUX/MAC testing
    std::cout << "HOME: " << cutl::getenv("HOME", "not found") << std::endl;
}

5. 執行結果

---------------------------------------------TestGetEnv---------------------------------------------
getenv for PATH, result:
/usr/local/bin:/usr/local/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/usr/local/go/bin
USERPROFILE: [2024-06-21 21:32:28.863][E]]0x7ff85b8d5fc0](cutl) [sysutil.cpp:208:getenv] variable [USERPROFILE] not set, fallback to not found
not found
PROCESSOR_ARCHITECTURE: [2024-06-21 21:32:28.863][E]]0x7ff85b8d5fc0](cutl) [sysutil.cpp:208:getenv] variable [PROCESSOR_ARCHITECTURE] not set, fallback to not found
not found
HOME: /Users/spencer

6. 原始碼地址

更多詳細程式碼,請檢視本人寫的C++ 通用工具庫: common_util, 本專案已開源,程式碼簡潔,且有詳細的文件和Demo。

相關文章