0

大家好,我使用此代码查找包含的行 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);

        ...
4

1 回答 1

1

您可以使用std::string::find()andstd::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 ( /*...*/ );
于 2013-06-24T19:36:49.177 回答