您好,登錄后才能下訂單哦!
在C++中,可以使用第三方庫(kù)如zlib或minizip來實(shí)現(xiàn)文件壓縮和解壓縮功能。以下是一個(gè)簡(jiǎn)單的示例代碼,展示了如何使用minizip庫(kù)來實(shí)現(xiàn)文件的壓縮和解壓縮:
#include <iostream>
#include "minizip/zip.h"
#include "minizip/unzip.h"
void compressFile(const std::string& filePath) {
zipFile zf = zipOpen((filePath + ".zip").c_str(), APPEND_STATUS_CREATE);
if (zf == NULL) {
std::cerr << "Error opening zip file" << std::endl;
return;
}
zip_fileinfo zi = {};
zipOpenNewFileInZip(zf, (filePath + ".txt").c_str(), &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION);
FILE* file = fopen(filePath.c_str(), "rb");
if (file == NULL) {
std::cerr << "Error opening file" << std::endl;
zipClose(zf, NULL);
return;
}
char buf[1024];
int len;
while ((len = fread(buf, 1, sizeof(buf), file)) > 0) {
zipWriteInFileInZip(zf, buf, len);
}
fclose(file);
zipCloseFileInZip(zf);
zipClose(zf, NULL);
std::cout << "File compressed successfully" << std::endl;
}
void decompressFile(const std::string& zipFilePath) {
unzFile uf = unzOpen(zipFilePath.c_str());
if (uf == NULL) {
std::cerr << "Error opening zip file" << std::endl;
return;
}
unz_file_info fi = {};
unzGetCurrentFileInfo(uf, &fi, NULL, 0, NULL, 0, NULL, 0);
unzOpenCurrentFile(uf);
char buf[1024];
FILE* file = fopen("output.txt", "wb");
if (file == NULL) {
std::cerr << "Error opening file" << std::endl;
unzCloseCurrentFile(uf);
unzClose(uf);
return;
}
int len;
while ((len = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) {
fwrite(buf, 1, len, file);
}
fclose(file);
unzCloseCurrentFile(uf);
unzClose(uf);
std::cout << "File decompressed successfully" << std::endl;
}
int main() {
compressFile("test.txt");
decompressFile("test.txt.zip");
return 0;
}
在上面的示例中,compressFile()
函數(shù)用于壓縮文件,decompressFile()
函數(shù)用于解壓縮文件。需要注意的是,示例中使用的是minizip庫(kù),需要提前下載并編譯該庫(kù)。壓縮和解壓縮文件的過程都是通過minizip庫(kù)提供的接口函數(shù)來實(shí)現(xiàn)的。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。