-3

I want to search for a string in a text file and delete the whole line when it's found. I want to write this in C++.

I've tried solutions in C#, and I've tried creating temporary files. Nothing works for me.

Here's my code so far:

 void MainForm::WriteToTextFile(){

   ifstream  stream("text.txt");
   string line;
   bool found = false;
   while (std::getline(stream, line) && !found)
   {
    if (line.find("Delete_This_Line") != string::npos){ // WILL    SEARCH "Delete_This_Line" in file
        found = true;
        line.replace(line.begin(), line.end(), "\n");
       stream.close();
      }

I expected that the text file would be modified but nothing has changed.

Thelouras
  • 852
  • 1
  • 10
  • 30

3 Answers3

2

You don't write anything to the file.

And for text files, you can't simply "replace" text, not unless the replacement is the exact same length as the old text you want replaced.

One common way to solve your problem is to read from the original file, writing to a temporary file. When you find the text you want to be replaced then you write the new text to the temporary file. Once you're done then you close both files, and rename the temporary file as the original file, replacing it with your new modified content.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You modify only a string in the memory, how can you expect that change the content of the read file ?

Note also to continue to try to read into the file while you closed it, you test found too late after the getline(), and is more simple to just add a break

bruno
  • 32,421
  • 7
  • 25
  • 37
0

std::getline duplicates the line to another string object inside memory. Modifying that string will not change the contents of the file.

A possible solution is to recreate the file using input and output file streams and avoid copying just the desired line. Here is an untested example:

#include <fstream>
#include <cstdio>
#include <string>
#include <iostream>

using namespace std;

bool replace_line(string filename, string key, string new_content) 
{
    {
        ifstream stream(filename);
        ofstream ofs(filename + ".out");
        string line;

        bool found = false;
        while (std::getline(stream, line))
        {
            if (line.find(key) != string::npos){ 
                found = true;
                ofs << new_content;
            } else {
                ofs << line;
            }
        }
    }

    remove(file);
    rename(file + ".out", filename);

    return found;
}
Anton Angelov
  • 1,223
  • 7
  • 19