gzipc.cpp

来自「压缩算法的C语言源程序」· C++ 代码 · 共 89 行

CPP
89
字号
/*
   gzipc.cpp
   GZIP decompression example
   Warning: This is in early testing stage... It DOES NOT work for all gzip
   files!!
*/
#include <stdio.h>
#include <compress.h>

typedef struct GZIPHeader
{
   word id     PACKED;
   byte cm     PACKED;
   struct {
      unsigned ftext    : 1;
      unsigned fhcrc    : 1;
      unsigned fextra   : 1;
      unsigned fname    : 1;
      unsigned fcomment : 1;
      unsigned reserved : 3;
   } flag      PACKED;
   dword mtime PACKED;
   byte xfl    PACKED;
   byte os     PACKED;
} GZIPHeader;

// loads a gzip file
STREAM *LoadGZIP(const char *filename)
{
   STREAM *fp, *buf;
   GZIPHeader h;
   long pos, size;

   fp = stream_open(filename,"rb");
   if(!fp) return NULL;

   stream_read(&h,sizeof(GZIPHeader),1,fp);
   if(h.id != 0x8b1f || h.cm != 8) return NULL;

   if(h.flag.fextra) stream_seek(fp,stream_getw(fp),SEEK_CUR);
   if(h.flag.fname) while(stream_getc(fp));
   if(h.flag.fcomment) while(stream_getc(fp));
   if(h.flag.fhcrc) stream_getw(fp);
   pos = stream_tell(fp);
   stream_seek(fp,-4L,SEEK_END);
   size = stream_getd(fp);
   stream_seek(fp,pos,SEEK_SET);
   buf = stream_alloc(size);
   if(!buf) {
      stream_close(fp);
      return 0;
   }
   inflate(buf,fp,size);

   stream_seek(buf,0L,SEEK_SET);

   stream_close(fp);

   return buf;
}

int main()
{
   STREAM *in, *out;

   printf("GZIP decoder... testing...\n");
   printf("Loading file `test.gz' ...\n");
   in = LoadGZIP("test.gz");
   if(!in) {
      fprintf(stderr,"Can't load GZIP file.");
      return 1;
   }
   out = stream_open("test.exe","wb");
   if(!out) {
      fprintf(stderr,"Couldn't open `test.exe'.\n");
      stream_close(in);
      return 1;
   }

   printf("Writing to file `test.exe' ...\n");
   int ch;
   while((ch = stream_getc(in)) != EOF) stream_putc(ch,out);
   stream_close(in);
   stream_close(out);

   printf("Done.\n");
   return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?