1

我想测试压缩和解压功能:compress() uncompresss()由ZLIB库提供;写如下代码打开一个已经存在的文件,在while()循环里面读取文件内容已经存在,压缩部分写入单个文件,解压部分写入另一个文件,代码如下图,已经存在的文件(originalFile)的大小大约78K,第一次进入while()循环压缩解压返回值为0,这样第一次进入成功,但是第二次和后面几次进入,返回值为-5(根据官方文档,缓冲的输出大小并没有大到包含内容),为什么?哪里错了?非常感谢你!

enter code here

#include <string>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include "zlib.h"
int main()
{
    unsigned long int fileLength;
    unsigned long int readLength;
    unsigned long int compressBufLength;
    unsigned long int uncompressLength;
    unsigned long int offset;

    unsigned char *readBuf = new unsigned char[512];//the readbuf of the exist file content
    unsigned char *compressBuf = new unsigned char[512];//the compress buffer   
    unsigned char *uncompressBuf = new unsigned char[512];//the uncompress  content buffer
    FILE *originalFile = fopen("/lgw150/temp/src/lg4/original.lg4","a+");//the exist file
    FILE *compressedFile = fopen("/lgw150/temp/src/lg4/compressed.lg4","a+");//compressfile
    FILE *uncompressFile = fopen("/lgw150/temp/src/lg4/uncompressed.lg4","a+");//

    fseek(originalFile,0,2);
    fileLength = ftell(originalFile);
    offset = 0;//
       while(offset <fileLength)//
    {


        printf("offset=%lu;fileLength=%lu\n",offset,fileLength);
        memset(readBuf,0,512);
        memset(compressBuf,0,512);
        memset(uncompressBuf,0,512);
        fseek(originalFile,offset,0);//
        readLength = fread(readBuf,sizeof(char),512,originalFile);
        offset += readLength;//
        int compressValue = compress(compressBuf,&compressBufLength,readBuf,readLength);
        int fwriteValue = fwrite(compressBuf,sizeof(char),compressBufLength,compressedFile);//
        printf("compressValue = %d;fwriteLength = %d;compressBufLength=%lu;readLength = %lu\n",compressValue,fwriteValue,compressBufLength,readLength);

        int uncompressValue = uncompress(uncompressBuf,&uncompressLength,compressBuf,compressBufLength);//
        int fwriteValue2= fwrite(uncompressBuf,sizeof(char),uncompressLength,uncompressFile);//
    }
    fseek(originalFile,0,0);
    fseek(compressedFile,0,0);
    fseek(uncompressFile,0,0);
    if(originalFile != NULL)
    {
        fclose(originalFile);
        originalFile = NULL;
    }

   if(compressedFile != NULL)
    {
        fclose(compressedFile);
        compressedFile = NULL;
    }
     if(uncompressFile != NULL)
    {
        fclose(uncompressFile);
        uncompressFile = NULL;
    }

    delete[] readBuf;
    delete[] compressBuf;
    delete[] uncompressBuf;
return 0;


}

enter code here
4

1 回答 1

7

首先,您得到“缓冲输出大小不足以包含内容”的原因是因为缓冲输出大小不足以包含内容。如果您给不可压缩的数据进行压缩,它将扩展数据。因此,如果输入为 512 字节,则 512 字节不够大。使用 compressBound() 函数进行最大扩展,以调整压缩输出缓冲区的大小。

其次,一次压缩 512 个字节是愚蠢的。您没有为压缩算法提供足够的数据来处理,以便获得您应该从压缩中获得的里程。您一次读取 512 字节块的应用程序不应使用 compress() 和 uncompress()。您应该使用为此目的而编写的 deflate() 和 inflate()——通过压缩和解压缩引擎提供数据块。

您需要阅读zlib.h。所有的。您还可以查看示例(在阅读 zlib.h 之后)。

于 2012-07-20T17:52:13.070 回答