Search code examples
c++c++11fstream

Preventing line repeats in files in C++


I apologize before-hand if this question was already asked and my google skills failed me.

I'm making a simple console game with ncurses and I wanted to include this locked zip folder with extra lore, bonus material, etc...

I can write the codes to the file just fine but for whatever reason when I revisit the place that wrote the text to the file it repeats itself. I've tried looking for a solution and haven't found one so this is my last resort.

basic information: I use windows but I want the program to be cross-platform. If any more information is required I'd be glad to provide it.

EDIT 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: ZWdOFMRmeE\n";
            myFile.close();
            break;
        }
    }
    checkFile.close();
}

EDIT 2: I'm not trying to overwrite any part of the other file. This code is "supposed" to check if the line above is already written in the file and if it isn't, write it. If the line already exists within the file I don't want it to write the same line again (and I'm using ios::app so that it doesn't overwrite anything already in the file.

Thanks in advance for the help.

EDIT 3: working now thanks to twalberg.

Final Code:

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: ZWdOFMRmeE\n";
        myFile.close();
    }
    checkFile.close();
}

Solution

  • Your current logic is a little off. You are reading the first line of the file, and if that line doesn't match, you append the string and break out of the loop. What you need is a structure more like this, checking each line of the file, and only then deciding whether to append your string:

    // 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