Deleting specific line from file

前端 未结 3 854
迷失自我
迷失自我 2020-11-30 10:40

These are the contents of my example file:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA FIND ME akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

I need to find

相关标签:
3条回答
  • 2020-11-30 11:22

    Try this:

    line.replace(line.find(deleteline),deleteline.length(),"");
    
    0 讨论(0)
  • 2020-11-30 11:24

    I'd like to clarify something. Although the answer provided by gmas80 could work, for me, it didn't. I had to modify it somewhat, and here's what I ended up with:

    position = line.find(deleteLine);
    
    if (position != string::npos) {
        line.replace(line.find(deleteLine), deleteLine.length(), "");
    }
    

    Another thing that didn't satisfy me was that it left blank lines in the code. So I wrote another thing to delete the blank lines:

    if (!line.empty()) {
        temp << line << endl;
    }
    
    0 讨论(0)
  • 2020-11-30 11:26

    In case anyone would like it I have converted Venraey's useful code into a function:

    #include <iostream>
    #include <fstream>
        
    void eraseFileLine(std::string path, std::string eraseLine) {
        std::string line;
        std::ifstream fin;
        
        fin.open(path);
        // contents of path must be copied to a temp file then
        // renamed back to the path file
        std::ofstream temp;
        temp.open("temp.txt");
    
        while (getline(fin, line)) {
            // write all lines to temp other than the line marked for erasing
            if (line != eraseLine)
                temp << line << std::endl;
        }
    
        temp.close();
        fin.close();
    
        // required conversion for remove and rename functions
        const char * p = path.c_str();
        remove(p);
        rename("temp.txt", p);
    }
    
    0 讨论(0)
提交回复
热议问题