Qt - Writing a file with QTextStream adds empty new lines to the text

Alaa Elrifaie picture Alaa Elrifaie · Jul 20, 2014 · Viewed 23.2k times · Source

I'm using the following code to write some text to a file:

QFile caFile(outputFolder + "file.extension");
caFile.open(QIODevice::WriteOnly | QIODevice::Text);

if(!caFile.isOpen()){
    qDebug() << "- Error, unable to open" << "outputFilename" << "for output";
}
QTextStream outStream(&caFile);
outStream << "First Line\nSecond Line\nThird Line";
caFile.close();

It's working like a charm, but with a little problem .. The text file should look like this:

First Line
Second Line
Third Line

But instead, it looks like this:

First Line

Second Line

Third Line

What's the problem here?

Answer

lpapp picture lpapp · Jul 21, 2014

It works for me like a charm.

input.txt

DA3MTkyMjE0NDdaFw0xODA2MDYyMjE0NDdaMDcxEzARBgNVBAMMCnVqY2E2bjku
anAxEzARBgNVBAoMCnZtamMgMm5vYjMxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz0+a0BEJEkPwNq7BEplV81+++wzonVAWWcqe

main.cpp

#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QByteArray>

int main()
{
    QFile inFile("input.txt");
    inFile.open(QIODevice::ReadOnly | QIODevice::Text);
    QByteArray inputData = inFile.readAll();

    QFile caFile("output.txt");
    caFile.open(QIODevice::WriteOnly | QIODevice::Text);

    if(!caFile.isOpen()){
        qDebug() << "- Error, unable to open" << "outputFilename" << "for output";
    }
    QTextStream outStream(&caFile);
    outStream << inputData;
    caFile.close();
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

output.txt

DA3MTkyMjE0NDdaFw0xODA2MDYyMjE0NDdaMDcxEzARBgNVBAMMCnVqY2E2bjku
anAxEzARBgNVBAoMCnZtamMgMm5vYjMxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz0+a0BEJEkPwNq7BEplV81+++wzonVAWWcqe