大家好我使用此代码查找包含seta r_fullscreen "0"
的行,如果此行的值为0,则返回MessageBox但我的问题是seta r_fullscreen
的值是否为“0”所以我怎么样可以在此行中将此值替换为“1”吗?
ifstream cfgm2("players\\config_m2.cfg",ios::in);
string cfgLine;
Process32First(proc_Snap , &pe32);
do{
while (getline(cfgm2,cfgLine)) {
if (string::npos != cfgLine.find("seta r_fullscreen")){
if (cfgLine.at(19) == '0'){
MessageBox(NULL,"run in full Screen mod.","ERROR", MB_OK | MB_ICONERROR);
...
答案 0 :(得分:1)
您可以使用std::string::find()
和std::string::replace()
执行此操作。找到包含配置说明符seta r_fullscreen
的行后,您可以执行以下操作。
std::string::size_type pos = cfgLine.find("\"0\"");
if(pos != std::string::npos)
{
cfgLine.replace(pos, 3, "\"1\"");
}
您不应该假设配置值"0"
位于特定的偏移量,因为r_fullscreen
和"0"
之间可能还有其他空格。
在看到您的其他注释后,您需要在更改完成后更新配置文件。您对字符串所做的更改仅适用于内存中的副本,并且不会自动保存到文件中。加载和更改后,您需要保存每一行,然后将更新保存到文件中。您还应该在do/while
循环之外移动更新配置文件的过程。如果你不这样做,你将为你检查的每个进程读取/更新文件。
以下示例可以帮助您入门。
#include <fstream>
#include <string>
#include <vector>
std::ifstream cfgm2("players\\config_m2.cfg", std::ios::in);
if(cfgm2.is_open())
{
std::string cfgLine;
bool changed = false;
std::vector<std::string> cfgContents;
while (std::getline(cfgm2,cfgLine))
{
// Check if this is a line that can be changed
if (std::string::npos != cfgLine.find("seta r_fullscreen"))
{
// Find the value we want to change
std::string::size_type pos = cfgLine.find("\"0\"");
if(pos != std::string::npos)
{
// We found it, not let's change it and set a flag indicating the
// configuration needs to be saved back out.
cfgLine.replace(pos, 3, "\"1\"");
changed = true;
}
}
// Save the line for later.
cfgContents.push_back(cfgLine);
}
cfgm2.close();
if(changed == true)
{
// In the real world this would be saved to a temporary and the
// original replaced once saving has successfully completed. That
// step is omitted for simplicity of example.
std::ofstream outCfg("players\\config_m2.cfg", std::ios::out);
if(outCfg.is_open())
{
// iterate through every line we have saved in the vector and save it
for(auto it = cfgContents.begin();
it != cfgContents.end();
++it)
{
outCfg << *it << std::endl;
}
}
}
}
// Rest of your code
Process32First(proc_Snap , &pe32);
do {
// some loop doing something I don't even want to know about
} while ( /*...*/ );