在C++中防止文件中的行重复

Preventing line repeats in files in C++

本文关键字:C++ 文件      更新时间:2023-10-16

如果这个问题已经被问到了,我的谷歌技能让我失望了,我很抱歉。

我正在用ncurses制作一个简单的主机游戏,我想包括这个锁定的zip文件夹,里面有额外的传说、奖励材料等…

我可以很好地将代码写入文件,但无论出于什么原因,当我重新访问将文本写入文件的地方时,它都会重复。我一直在寻找解决方案,但没有找到,所以这是我的最后手段。

基本信息:我使用windows,但我希望程序是跨平台的。如果需要更多信息,我很乐意提供。

编辑1:

std::ifstream checkFile("Unlocks.txt");
if(checkFile.is_open())
{
    std::string data;
    std::string fernox = "Unlock for Fernox Piraxis File";
    while(std::getline(checkFile, data))
    {
        if(data.find(fernox) == std::string::npos)
        {
            std::ofstream myFile("Unlocks.txt", std::ios::app);
            myFile << "Unlock for Fernox Piraxis File: ZWdOFMRmeEn";
            myFile.close();
            break;
        }
    }
    checkFile.close();
}

编辑2:我没有试图覆盖其他文件的任何部分。这个代码"应该"检查上面的行是否已经写在文件中,如果没有,就写它。如果该行已经存在于文件中,我不希望它再次写同一行(我使用ios::app,这样它就不会覆盖文件中已经存在的任何内容。

提前感谢您的帮助。

编辑3:多亏了twalberg现在还在工作。

最终代码:

std::ifstream checkFile ("Unlocks.txt");
if(checkFile.is_open())
{
    bool found = false;
    std::string data;
    std::string fernox ("Unlock for Fernox Piraxis File");
    while(std::getline(checkFile, data))
    {
        if(data.find(fernox) != std::string::npos)
        {
            found = true;
            break;
        }
    }
    if(!found)
    {
        std::ofstream myFile("Unlocks.txt", std::ios::app);
        myFile << "Unlock for Fernox Piraxis File: ZWdOFMRmeEn";
        myFile.close();
    }
    checkFile.close();
}

您当前的逻辑有点错误。您正在读取文件的第一行,如果该行不匹配,则附加字符串并中断循环。你需要的是一个更像这样的结构,检查文件的每一行,然后再决定是否附加你的字符串:

// open file
bool found = false;
while (std::getline(checkFile, data))
{  if (data.find(fernox) != std::string::npos) // we found a match
   { found = true;
     break;
   }
}
if (!found)
{ // append string here
}
// close file