Ralph De Guzman
Ralph De Guzman

Reputation: 209

How to delete a specific row in a text file using fstream

Good Day! My problem is I should delete a whole specific row in my text file. But instead, I am just replacing it with white space. Actually, I have no idea how to delete the row. Here is my code:

fstream fs("FoodList.txt");
//charPos here is the position in file where I should begin deleting.
fs.seekp(charPos);
//I loop 100 times because I am sure that each row is 100 characters.
for (int i = 0; i < 100; i++)
{
    //What I really want to do is to delete the whole row
    fs << " ";
}

My text file would look like this: Before:

apple
banana
carrot
cherry

After(if I choose charPos = 3):

apple
banana
cherry

By the way, I have already made the Update part where I can EDIT specific rows. Any help will be appreciated! :)

Upvotes: 0

Views: 6385

Answers (2)

Felix Petersilie
Felix Petersilie

Reputation: 1

I don't know if it is a bad way to do this, but i have found a simple way to do this.

    while(!fs.eof())
    {
        fs << '\0';
    }

This code will erase the whole text after your position in the File.

by the way: fs.eof() tells you if you are at the end of the stream

for setting your position you can use this:

fs.seekp(streampos pos);

If you just want to delete the text between yout position an the next spaces, Tabstop or enter you just use the the single line shown in the loop, but I think you know that (:

I hope this will help you

Upvotes: 0

stefaanv
stefaanv

Reputation: 14392

The easiest way is to read in the file, write out to a temporary file, excluding the selected line and to move the temporary file to the original one.

Upvotes: 3

Related Questions