Сегодня мы научимся работать с zip-архивами, используя почти родной класс QZipReader и QZipWriter. Напрямую их подключить не получится, но эти файлы есть в исходниках Qt в папке: \src\gui\text.
Копируем qzipreader_p.h и qzipwriter_p.h к себе в проект и добавляем их.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "qzipreader_p.h" | |
#include "qzipwriter_p.h" |
Используя эти классы, работа с архивами становится такой же простой, как и работа с обычными файлами.
Чтение текстового файла внутри архива:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
QString text; | |
QZipReader *zip("zip_file.zip", QIODevice::ReadOnly); | |
if (zip.status() == QZipReader::NoError) | |
{ | |
QByteArray data = zip.fileData("text_file.txt"); | |
QTextStream stream(&data); | |
text = stream.readAll(); | |
zip.close(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
QList<QZipReader::FileInfo> file_list = zip.fileInfoList(); |
Создание архива:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
QString text; //<-append some text in | |
QZipWriter *zip("zip_file.zip", QIODevice::WriteOnly); | |
if (zip.status() == QZipWriter::NoError) | |
{ | |
QByteArray data; | |
QTextStream stream(&data); | |
stream << text; | |
stream.flush(); | |
zip.addFile("text_file.txt", data); | |
zip.close(); | |
} |
Комментариев нет:
Отправить комментарий