VC++ 添加用户环境变量

如果已知很多环境变量,每次换机器都是相同配置,环境变量配置窗口操作觉得麻烦,可以考虑这个代码直接注册。

只需要在reg.txt中按行写入:环境变量名=环境变量值


程序地址:http://download.csdn.net/download/jiyanglin/10170928



这是完整的代码实现:

#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <atlstr.h>
#include <Windows.h>
using namespace  std;
class RegEnv
{
public:
void Run()
{
HKEY hKey;
if(RegOpenKey(HKEY_CURRENT_USER, _T("Environment"), &hKey) != ERROR_SUCCESS)
{
cout<<"打开用户环境变量失败"<<endl;
return ;
}


cout<<"打开reg.txt文件,读入每行key=val进行用户环境变量注册"<<endl;
cout<<"除path是附加内容外,其余都是存在数值则直接替换"<<endl;
cout<<"有空行或者不是key=val内容会自动跳过的...."<<endl;
cout<<"======================"<<endl;
cout<<"======================"<<endl;
cout<<"======================"<<endl;


cout<<"按任意键开始运行"<<endl;
getchar();


cout<<endl;
cout<<endl;
cout<<endl;




ifstream ifs("reg.txt");
string strline;
vector<string> strVec;
while (getline(ifs,strline))
{
strVec.clear();
SplitString(strVec,strline,'=');
if (strVec.size() != 2) continue;

Reg(hKey,strVec[0],strVec[1]);
}
strVec.swap(vector<string>());
ifs.close();
}
private:
void SplitString(vector<string> &vecStr,string str,char split = ',')
{
string strLeft;
size_t pos = str.find(split);
while(string::npos != pos)
{
strLeft = str.substr(0,pos);
vecStr.push_back(strLeft);
str = str.substr(pos + 1);
pos = str.find(split);
}


if(str != "")
vecStr.push_back(str);
}
bool machstr(char str,char ch,char CH)
{
if (str == ch || str == CH) return true;
return false;
}
string GetPathVal(HKEY hKey,string strName)
{
string str;
if (strName.length() != 4) return str;
if (!machstr(strName[0],'p','P')) return str;
if (!machstr(strName[1],'a','A')) return str;
if (!machstr(strName[2],'t','T')) return str;
if (!machstr(strName[3],'h','H')) return str;


LPBYTE  data[2048] = {0};
DWORD lValueSize;
if (RegQueryValueExA(hKey,"path",NULL,NULL,(LPBYTE)data,&lValueSize) == ERROR_SUCCESS)
{
CStringA re;
re.Format("%s",data);
str = re.GetBuffer();



return str;
}
void Reg(HKEY hKey,string strName,string strValue)
{
string val = GetPathVal(hKey,strName);
if (val != "") strValue = val + ";" + strValue;
int regType = REG_SZ;
if (strValue.find("%")!= string::npos) regType = REG_EXPAND_SZ;


if(RegSetValueExA(hKey,strName.c_str(),NULL,regType,(BYTE*)strValue.c_str(),strValue.length()) == ERROR_SUCCESS)
{
cout<<"注册成功: "<<strName<<"="<<strValue<<endl;
}
}
};
void main()
{
RegEnv().Run();
}

发布了42 篇原创文章 · 获赞 7 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/jiyanglin/article/details/78882765
今日推荐