c++ - 为什么这种理论上跨平台的代码不会改变 Windows 上的环境变量?

标签 c++ windows visual-studio-2010 boost boost-filesystem

所以我尝试下一个代码:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <boost/filesystem/v3/path.hpp>
#include <boost/filesystem/v3/operations.hpp>
#ifdef WIN
#include <Windows.h>
#endif

void setEnviromentVariable(std::string name, boost::filesystem::path value)
{
    if ( getenv (name.c_str())==NULL)
    {
        std::cout << "Hit ENTER to restart application in order to agree with the next terms of use: do not eat my bytes!)" << std::endl;
        std::stringstream VAR;
        VAR << name<< "=" << value.native().c_str();
           #ifdef WIN
        std::stringstream VAL;
        VAL << value.native().c_str();
        if( !SetEnvironmentVariable(TEXT(name.c_str()), TEXT(VAL.str().c_str()))) 
        {
            printf("SetEnvironmentVariable failed (%d)\n", GetLastError()); 
        }
          #else
        setenv(VAR.str().c_str());
          #endif
        std::cin.get();

    }

}
int main(int argc, char *argv[])
{
        boost::filesystem::path full_path( boost::filesystem::current_path() / "assets/" );
        setEnviromentVariable("TCL_LIBRARY", full_path);
}

我的代码有什么问题?为什么它不设置任何环境变量,为什么它不显示任何错误? ( WIN code is based on this. )

最佳答案

putenv() 将指定的字符串指针放在环境 vector 中;它不会复制字符串值。

The string pointed to by string becomes part of the environment. A program should not alter or free the string, and should not use stack or other transient string variables as arguments to putenv().

因此当 VAR 超出范围时,环境包含一个垃圾指针并且尝试访问它会出现段错误或返回垃圾。

关于c++ - 为什么这种理论上跨平台的代码不会改变 Windows 上的环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6589865/

相关文章:

c++ - 如何在未知输入类型下使用 cin?

c++ - 析构函数调用

c - 十六进制编辑器和 OllyDbg 中的字节

c++ - 如何在 C++ 中执行 SQLite 语句

c++ - VC++目录表现奇怪

wpf - Silverlight 4等效于WPF “x:static”

iphone - 如何下载没有文件扩展名的url源代码?

c++ - C++中的PLC功能 block 库

windows - 使用 Mingw 编译器编译 google 测试框架

visual-studio-2010 - 适用于 Windows Phone 的 Visual Studio Express 未显示正确的设计 View