Qt - 使用QTextStream编写文件会在文本中添加空的新行

时间:2014-07-20 21:29:39

标签: qt qstring qtextstream

我正在使用以下代码将一些文本写入文件:

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();

它的工作就像一个魅力,但有点问题.. 文本文件应如下所示:

First Line
Second Line
Third Line

但相反,它看起来像这样:

First Line

Second Line

Third Line

这里有什么问题?

2 个答案:

答案 0 :(得分:3)

它对我来说就像一个魅力。

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

构建并运行

qmake && make && ./main

output.txt的

DA3MTkyMjE0NDdaFw0xODA2MDYyMjE0NDdaMDcxEzARBgNVBAMMCnVqY2E2bjku
anAxEzARBgNVBAoMCnZtamMgMm5vYjMxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz0+a0BEJEkPwNq7BEplV81+++wzonVAWWcqe

答案 1 :(得分:2)

QString filename = "";//file adding path
QFile file(filename);
file.open(QIODevice::ReadWrite);
QTextStream stream(&file);
stream << "abc\nxyz" << endl;
file.close();


output:abc
       xyz