qtquazip

Write QStream to file in zip with QuaZip


I want to write a QString in a textfile in a ziparchive with QuaZip. I use Qt Creator on WinXP. With my code the text-file in the archive is created but empty.

QDomDocument doc;
/* doc is filled with some XML-data */

zipfile = new QuaZip("test.zip");
zipfile->open(QuaZip::mdCreate);
QuaZipFile file(zipfile);
file.open(QIODevice::WriteOnly, QuaZipNewInfo("foo.xml"));

QTextStream ts ( &file );
ts << doc.toString();

file.close();
zipfile.close();

When I try with a QFile it works as expected:

QDomDocument doc;
/* doc is filled with some XML-data */

QFile file("test.xml");
file.open(QIODevice::WriteOnly);

QTextStream ts ( &file );
ts << doc.toString();

file.close();

I find the right content in test.xml, so the String is there, but somehow the QTextStream doesn't want to work with the QuaZipFile.

When I do it with a QDataStream instead of QTextStream there is an output, but not a correct one. QDomDocument doc; /* doc is filled with some XML-data */

zipfile = new QuaZip("test.zip");
zipfile->open(QuaZip::mdCreate);
QuaZipFile file(zipfile);
file.open(QIODevice::WriteOnly, QuaZipNewInfo("foo.xml"));

QDataStream ts ( &file );
ts << doc.toString();

file.close();
zipfile.close();

The foo.xml in the test.zip is filled with some data, but wrong formatted (between each character is an extra 'nul'-character).

How can I write the String in the textfile in the zip-archive?

Thanks, Paul


Solution

  • You don't need QTextStream or QDataStream to write a QDomDocument to a ZIP file.

    You can simply do the following:

    QDomDocument doc;
    /* doc is filled with some XML-data */
    
    zipfile = new QuaZip("test.zip");
    zipfile->open(QuaZip::mdCreate);
    QuaZipFile file(zipfile);
    file.open(QIODevice::WriteOnly, QuaZipNewInfo("foo.xml"));
    
    // After .toString(), you should specify a text codec to use to encode the
    // string data into the (binary) file. Here, I use UTF-8:
    file.write(doc.toString().toUtf8());
    
    file.close();
    zipfile->close();