Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting specific line from file

Tags:

c++

These are the contents of my example file:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA FIND ME akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

I need to find and delete the 'FIND ME' inside of the file so the output would look like this:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

I have tried the following method of doing getline and then writing all of the contents except the FIND ME into a temporary file and then rename the temporary file back.

string deleteline;
string line;

ifstream fin;
fin.open("example.txt");
ofstream temp;
temp.open("temp.txt");
cout << "Which line do you want to remove? ";
cin >> deleteline;



while (getline(fin,line))
{
    if (line != deleteline)
    {
    temp << line << endl;
    }
}

temp.close();
fin.close();
remove("example.txt");
rename("temp.txt","example.txt");

but it doesn't work. Just as a side note: the file has NO newline/linefeeds. So the file contents are all written in 1 line.

EDIT:

FIXED CODE:

while (getline(fin,line))
{
    line.replace(line.find(deleteline),deleteline.length(),"");
    temp << line << endl;

}

This gets me the results I expected. Thank you everyone for helping!

like image 354
Venraey Avatar asked Oct 26 '14 18:10

Venraey


People also ask

How do you delete a specific line in a file in C?

Step 1 − Read file path and line number to remove at runtime. Step 2 − Open file in read mode and store in source file. Step 3 − Create and open a temporary file in write mode and store its reference in Temporary file. Step 4 − Initialize a count = 1 to track line number.

How do you delete a specific line in a file Linux?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.


1 Answers

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);
}
like image 59
Cuinn Herrick Avatar answered Oct 06 '22 18:10

Cuinn Herrick