[SOLVED] Erase empty lines from a text file in C++

Issue

I have a text file, which may contain some empty lines. I want to open this file and look for the empty lines. If an empty line exists then, I want to delete that line. I do not want to create a temporary file for this purpose. I want to edit the same file and close it afterwards.

I have already seen a couple of posts about similar problem but none of them worked for me.

void DeleteEmptyLines(const string& FilePath)
{
    //EXISTING File
    std::fstream FileStream;
    std::string CurrentReadLine;
    if (doesFileExist(FilePath))
    {
        FileStream.open(FilePath, std::fstream::in | std::fstream::out | std::fstream::app);

        //Read all the lines till the end of the file
        while(getline(FileStream, CurrentReadLine))
        {
            //Check if the line is empty
            if(CurrentReadLine.empty())
            {
                cout<<"Empty line found"<<endl;
                //DELETE THIS EMPTY LINE
            }
        }

        FileStream.clear();
        FileStream.close();
    }
    // else --->> do nothing
}

Current File (MyFile.txt):

Line1

Line2

Line3

What I need (MyFile.txt):

Line1
Line2
Line3

PS: I am using VS2010 on windows machine.

Solution

Simple solution. Reads file into a string skipping empty lines, then overwrites the file with the contents of the string.

void DeleteEmptyLines(const std::string &FilePath)
{
    std::ifstream in(FilePath);
    std::string line, text;
    while (std::getline(in, line))
        if !(line.empty() || line.find_first_not_of(' ') == std::string::npos)
            text += line + "\n"
    in.close();
    std::ofstream out(FilePath);
    out << text;
}

EDIT: @skm The new answer you posted does not erase lines with empty spaces, as you stated.

To fix this use this condition to make sure a line is not “empty”:

!(CurrentReadLine.empty() || CurrentReadLine.find_first_not_of(' ') == std::string::npos)

Answered By – cppxor2arr

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *