Continuing my work to clean up my eBooks I’ve written another little tool to help. I like for my eBooks to have two blank lines at the end of the file.

The only major caveat of this one is it assumes Unix end of lines. Meaning a single n character. In order for this to work correctly use of the dos2unix tool is necessary for files that use a different new line format.

fix_end_ebook_txt.cpp

/*
Copyright (c) 2008 John Schember <john@nachtimwald.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/*
Ensures that there are 3 newline characters at the end of the file (two blank
lines after the last of the text). This assumes Unix n line characters. Please
use dos2unix before running to ensure that the end of line characters are
correct.
*/

#include <QFile>
#include <QString>
#include <QTextStream>

int main(int argc, char **argv)
{
    // Stream to write errors to the console.
    QTextStream errStream(stderr);

    // Store for the contents of the ebook.
    QString content;

    // We need an ebook file to work on.
    if (argc != 2) {
        errStream << QObject::tr("Error: No input file") << endl;
        return 1;
    }

    QFile ebook(argv[1]);
    if (!ebook.open(QIODevice::ReadWrite | QIODevice::Text)) {
        errStream << QObject::tr("Error: Could not open") << endl;
        return 1;
    }

    // We use a QTextStream to actually work on the file.
    QTextStream ioStream(&ebook);

    // We want to see what the last 3 characters are at the end of the file.
    ioStream.seek(ebook.size() - 3);
    content = ioStream.read(3);

    // Move to the end of the file because we want to add newlines (n's) to
    // the end.
    ioStream.seek(ebook.size());

    // We want 3 newline (n) characters at the end of the file. Add them until
    // they total 3.
    for (int i = 0; i < (3 - content.count("n")); i++) {
        ioStream << "n" << flush;
    }

    ebook.close();

    return 0;
}