所以我尝试下一个代码:
#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 toputenv()
.
因此当 VAR
超出范围时,环境包含一个垃圾指针并且尝试访问它会出现段错误或返回垃圾。
关于c++ - 为什么这种理论上跨平台的代码不会改变 Windows 上的环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6589865/