Flexo1515
Flexo1515

Reputation: 1017

C++ reading and then editing a text file

I am wondering how to read in and edit a text file by searching for lines containing foobar and then erasing those lines only. Don't need a full program, if someone could just point me towards the right fstream functions.

Upvotes: 0

Views: 294

Answers (2)

Ionut Hulub
Ionut Hulub

Reputation: 6326

do something like this:

string sLine = "";
infile.open("temp.txt");

while (getline(infile, sLine))
{
  if (strstr(sLine, "foobar") != NULL)
    cout<<sLine;
  else
    //you don't want this line... it contains foobar
}

infile.close();
cout << "Read file completed!!" << endl;

here I have printed the output to the console, not back to the file, because this should point you in the right direction.

if you need a hint on how to print the lines to the file read below:

Save all the lines that don't contain foobar to a string. After you have read the whole file, close it, then open it with write permission and write the string to it. this will also overwrite the old content.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490028

#include <iostream>
#include <algorithm>
#include <string>

class line {
    std::string data;
public:
    friend std::istream &operator>>(std::istream &is, line &l) {
        std::getline(is, l.data);
        return is;
    }
    operator std::string() const { return data; }    
};

int main() {      
    std::remove_copy_if(std::istream_iterator<line>(std::cin),
                        std::istream_iterator<line>(),
                        std::ostream_iterator<std::string>(std::cout, "\n"),
                        [](std::string const &s) { 
                            return s.find("foobar") != std::string::npos;
                        });
    return 0;
}

Upvotes: 5

Related Questions