您可以使用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 (/*...*/);
你試過嗎? 'cfgLine.at(19)=「1'' – ruben2020
要更換哪裏 '1'?在字符串中還是在.cfg文件中? – Marius
在.cfg文件 – user2468671