2

我想用 QuaZip 在 ziparchive 的文本文件中写一个 QString。我在 WinXP 上使用 Qt Creator。使用我的代码,存档中的文本文件已创建但为空。

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

当我尝试使用 QFile 时,它​​按预期工作:

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

我在 test.xml 中找到了正确的内容,所以字符串在那里,但不知何故 QTextStream 不想与 QuaZipFile 一起使用。

当我使用 QDataStream 而不是 QTextStream 进行操作时,会有输出,但不是正确的。QDomDocument 文档;/* doc 填充了一些 XML 数据 */

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

test.zip 中的 foo.xml 填充了一些数据,但格式错误(每个字符之间有一个额外的“nul”字符)。

如何在 zip-archive 的文本文件中写入字符串?

谢谢,保罗

4

2 回答 2

4

您不需要 QTextStream 或 QDataStream 将 QDomDocument 写入 ZIP 文件。

您可以简单地执行以下操作:

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();
于 2012-07-13T21:02:32.333 回答
3

在最初的第一个示例中,您必须刷新流:

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();
ts.flush();

file.close();
zipfile.close();
于 2012-08-22T13:57:07.697 回答