LoginSignup
5
4

More than 5 years have passed since last update.

環境変数の取得(C++)

Last updated at Posted at 2015-12-09

ゲームのセーブデータのディレクトリをゲームと同じフォルダにするかAppDataに入れるか悩んでいる時ふと思いつき、書いてみました。

get_environment_variable.cpp
#include <cstdlib>
#include <string>
#include <stdexcept>

std::string get_environment_variable(const char* environment_name) {
    size_t buf;
    char buffer[1024];
    if (getenv_s(&buf, buffer, 1024, environment_name)) throw std::runtime_error("read error");
    if (buf == 0) throw std::runtime_error("not such environment variable");
    return std::string(buffer);
}

使用例

main.cpp
#include <iostream>
#include <stdexcept>
int main() {
    try {
        std::cout << get_environment_variable("UserProfile") << std::endl;
        return 0;
    }
    catch(std::exception &er){
        std::cout << er.what() << std::endl;
        return -1;
    }
}

実行結果とechoコマンドで呼んだ時の結果の比較

実行結果

GetEnvironmentApplication.png

echoコマンドで呼んだ時の結果

echo_result.png

絶対バッファーのサイズ無駄に大きい気がするけどまあいっか。
ゲーム作るうえで環境変数呼ぶなら日本語パスを想定しないといけないしね。
だってPC基本的なレベルまでしかできないという人とかはユーザー名日本語のこと多いしね。

@iwadonさんのアドバイスに基づいて作り直してみました。

get_environment_variable.cpp
#include <cstdlib>
#include <string>
#include <stdexcept>
std::string get_environment_variable(const char* environment_name) {
    size_t buf;
    if (getenv_s(&buf, NULL, 0, environment_name)) throw std::runtime_error("read error");
    if (buf == 0) throw std::runtime_error("not such environment variable");
    getenv_s(&buf, buffer, buf, environment_name);
    return std::string(buffer);
}

使い方は同じです。

@yumetodo さんによってさらに編集がかかりました。

get_environment_variable.cpp
#include <cstdlib>
#include <string>
#include <stdexcept>
std::string get_environment_variable(const char* environment_name) {
    size_t buf;
    if (getenv_s(&buf, NULL, 0, environment_name)) throw std::runtime_error("read error");
    if (buf == 0) throw std::runtime_error("not such environment variable");
    std::string buffer;
    buffer.resize(buf + 1);//reserve
    getenv_s(&buf, &buffer[0], buf, environment_name);
    buffer.resize(std::strlen(buffer.c_str()));//resize
    return buffer;
}

もちろん使い方は変わりません。

5
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4