linux系统环境下的zip解压程序, RTOS下需要修改一些参数。自测可以运行的

本文介绍了一个从项目中提炼出来的解压程序,详细展示了其代码实现,包括如何读取压缩文件、解析头部信息、处理不同类型的压缩块(如动态、固定和存储块),以及如何将解压后的文件内容写入到指定路径。程序还实现了文件名的提取和存储,能够处理多个文件的解压缩,并支持创建文件夹结构。
摘要由CSDN通过智能技术生成

经历了项目的摧残,最终版本的解压程序。

备注:

     参考网上关于gzip的源码与其他大神的案例。

编译指令:

gcc -D_GNU_SOURCE -o main main.c

/*
gcc -D_GNU_SOURCE *.c
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
//#include "inflate.h"

int load_zip_file(char *path);
static  char *start = NULL;
static int zipfilelength;
#define FILEPATH_MAX 100
#define MAX_WRITE_SIZE 1000000
static int large_little_flag = 0;

#define WSIZE 0x8000  

//---------------------------------------------------------------------------------------------------
#if 1
typedef unsigned char  uch;
typedef unsigned short ush;
typedef unsigned long  ulg;

typedef struct {
    uch *inbuf;
    int inbufsiz;
    uch *outbuf;
    int outcnt;
    unsigned int bb;
    unsigned int bk;
    unsigned int inptr;
    // unsigned int hufts;
} zip_t;

typedef struct {
    char filnamesave[100][100];
} cfilename_t;


enum zip_hdr_offset_enum {
    LOCAL_FILE_HDR_SIGNATURE,
    ZIP_VERSION_OFFSET = 4,
    ZIP_FLAG_OFFSET = 6,
    ZIP_METHOD_OFFSET = 8,
    ZIP_TIME_OFFSET = 10,
    ZIP_DATE_OFFSET = 12,
    ZIP_CRC32_OFFSET = 14,
    ZIP_COMPRESSED_SIZE_OFFSET = 18,
    ZIP_UNCOMPRESSED_SIZE_OFFSET = 22,
    ZIP_FILENAME_LENGTH_OFFSET = 26,
    ZIP_EXTRA_FIELD_LENGTH_OFFSET = 28,
    ZIP_FILENAME_OFFSET = 30
};

struct huft {
    uch e;                /* number of extra bits or operation */
    uch b;                /* number of bits in this code or subcode */
    union {
      ush n;              /* literal, length base, or distance base */
      struct huft *t;     /* pointer to next level of table */
    } v;
};

/* Tables for deflate from PKZIP's appnote.txt. */
static unsigned border[] = {    /* Order of the bit length code lengths */
    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
    35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 };
/* note: see note #13 above about the 258 in this list. */
static ush cplext[] = {         /* Extra bits for literal codes 257..285 */
    0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
    3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99 }; /* 99==invalid */
static ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
    257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
    8193, 12289, 16385, 24577 };
static ush cpdext[] = {         /* Extra bits for distance codes */
    0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
    7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
    12, 12, 13, 13 };

ush mask_bits[] = {
    0x0000,
    0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
    0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
};

int lbits = 9;          /* bits in base literal/length lookup table */
int dbits = 6;          /* bits in base distance lookup table */
              /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
#define BMAX 16         /* maximum bit length of any code (16 for explode) */
#define N_MAX 288       /* maximum number of codes in any set */

#define NEXTBYTE()  (uch)get_byte()
#define NEEDBITS(n) do {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}} while(0)
#define DUMPBITS(n) do {b>>=(n);k-=(n);}while(0)
#define get_byte()  pzip->inbuf[pzip->inptr++]

int huft_free(struct huft *t)
/* t: table to free */
/* Free the malloc'ed tables built by huft_build(), which makes a linked
list of the tables it made, with the links in a dummy first entry of
each table. */
{
    register struct huft *p, *q;
    /* Go through linked list, freeing from the malloced (t[-1]) address. */
    p = t;
    while (p != (struct huft *)NULL)
    {
      q = (--p)->v.t;
      free((char*)p);
      p = q;
    }
    return 0;
}

int huft_build(b, n, s, d, e, t, m)
unsigned *b;            /* code lengths in bits (all assumed <= BMAX) */
unsigned n;             /* number of codes (assumed <= N_MAX) */
unsigned s;             /* number of simple-valued codes (0..s-1) */
ush *d;                 /* list of base values for non-simple codes */
ush *e;                 /* list of extra bits for non-simple codes */
struct huft **t;        /* result: starting table */
int *m;                 /* maximum lookup bits, returns actual */
              /* Given a list of code lengths and a maximum table size, make a set of
              tables to decode that set of codes.  Return zero on success, one if
              the given code set is incomplete (the tables are still built in this
              case), two if the input is invalid (all zero length codes or an
              oversubscribed set of lengths), and three if not enough memory. */
{
    unsigned a;                   /* counter for codes of length k */
    unsigned c[BMAX + 1];           /* bit length count table */
    unsigned f;                   /* i repeats in table every f entries */
    int g;                        /* maximum code length */
    int h;                        /* table level */
    register unsigned i;          /* counter, current code */
    register unsigned j;          /* counter */
    register int k;               /* number of bits in current code */
    int l;                        /* bits per table (returned in m) */
    register unsigned *p;         /* pointer into c[], b[], or v[] */
    register struct huft *q;      /* points to current table */
    struct huft r;                /* table entry for structure assignment */
    struct huft *u[BMAX];         /* table stack */
    unsigned v[N_MAX];            /* values in order of bit length */
    register int w;               /* bits before this table == (l * h) */
    unsigned x[BMAX + 1];           /* bit offsets, then code stack */
    unsigned *xp;                 /* pointer into x */
    int y;                        /* number of dummy codes added */
    unsigned z;                   /* number of entries in current table */

                    /* Generate counts for each bit length */
    bzero(c, sizeof(c));
    p = b;  i = n;
    do {
      c[*p]++;                    /* assume all entries <= BMAX */
      p++;                      /* Can't combine with above line (Solaris bug) */
    } while (--i);
    if (c[0] == n)                /* null input--all zero length codes */
    {
      *t = (struct huft *)NULL;
      *m = 0;
      return 0;
    }

    /* Find minimum and maximum length, bound *m by those */
    l = *m;
    for (j = 1; j <= BMAX; j++)
      if (c[j])
        break;
    k = j;                        /* minimum code length */
    if ((unsigned)l < j)
      l = j;
    for (i = BMAX; i; i--)
      if (c[i])
        break;
    g = i;                        /* maximum code length */
    if ((unsigned)l > i)
      l = i;
    *m = l;

    /* Adjust last length count to fill out codes, if needed */
    for (y = 1 << j; j < i; j++, y <<= 1)
      if ((y -= c[j]) < 0)
        return 2;                 /* bad input: more codes than bits */
    if ((y -= c[i]) < 0)
      return 2;
    c[i] += y;

    /* Generate starting offsets into the value table for each length */
    x[1] = j = 0;
    p = c + 1;  xp = x + 2;
    while (--i) {                 /* note that i == g from above */
      *xp++ = (j += *p++);
    }

    /* Make a table of values in order of bit lengths */
    p = b;  i = 0;
    do {
      if ((j = *p++) != 0)
        v[x[j]++] = i;
    } while (++i < n);

    /* Generate the Huffman codes and for each, make the table entries */
    x[0] = i = 0;                 /* first Huffman code is zero */
    p = v;                        /* grab values in bit order */
    h = -1;                       /* no tables yet--level -1 */
    w = -l;                       /* bits decoded == (l * h) */
    u[0] = (struct huft *)NULL;   /* just to keep compilers happy */
    q = (struct huft *)NULL;      /* ditto */
    z = 0;                        /* ditto */

                    /* go through the bit lengths (k already is bits in shortest code) */
    for (; k <= g; k++)
    {
      a = c[k];
      while (a--)
      {
        /* here i is the Huffman code of length k bits for value *p */
        /* make tables up to required level */
        while (k > w + l)
        {
          h++;
          w += l;                 /* previous table always l bits */

                      /* compute minimum size table less than or equal to l bits */
          z = (z = g - w) > (unsigned)l?l : z;  /* upper limit on table size */
          if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
          {                       /* too few codes for k-w bit table */
            f -= a + 1;           /* deduct codes from patterns left */
            xp = c + k;
            while (++j < z)       /* try smaller tables up to z bits */
            {
              if ((f <<= 1) <= *++xp)
                break;            /* enough codes to use up j bits */
              f -= *xp;           /* else deduct codes from patterns */
            }
          }
          z = 1 << j;             /* table entries for j-bit table */

                      /* allocate and link in new table */
          if ((q = (struct huft *)malloc((z + 1) * sizeof(struct huft))) ==
            (struct huft *)NULL)
          {
            if (h)
              huft_free(u[0]);
            return 3;             /* not enough memory */
          }
          *t = q + 1;             /* link to list for huft_free() */
          *(t = &(q->v.t)) = (struct huft *)NULL;
          u[h] = ++q;             /* table starts after link */

                      /* connect to last table, if there is one */
          if (h)
          {
            x[h] = i;             /* save pattern for backing up */
            r.b = (uch)l;         /* bits to dump before this table */
            r.e = (uch)(16 + j);  /* bits in this table */
            r.v.t = q;            /* pointer to this table */
            j = i >> (w - l);     /* (get around Turbo C bug) */
            u[h - 1][j] = r;        /* connect to last table */
          }
        }

        /* set up table entry in r */
        r.b = (uch)(k - w);
        if (p >= v + n)
          r.e = 99;               /* out of values--invalid code */
        else if (*p < s)
        {
          r.e = (uch)(*p < 256?16 : 15);    /* 256 is end-of-block code */
          r.v.n = (ush)(*p);             /* simple code is just the value */
          p++;                           /* one compiler does not like *p++ */
        }
        else
        {
          r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
          r.v.n = d[*p++ - s];
        }

        /* fill code-like entries with r */
        f = 1 << (k - w);
        for (j = i >> w; j < z; j += f)
          q[j] = r;

        /* backwards increment the k-bit code i */
        for (j = 1 << (k - 1); i & j; j >>= 1)
          i ^= j;
        i ^= j;

        /* backup over finished tables */
        while ((i & ((1 << w) - 1)) != x[h])
        {
          h--;                    /* don't need to update q */
          w -= l;
        }
      }
    }
    /* Return true (1) if we were given an incomplete table */
    return y != 0 && g != 1;
}

int inflate_codes(pzip, tl, td, bl, bd)
zip_t *pzip;
struct huft *tl, *td;   /* literal/length and distance decoder tables */
int bl, bd;             /* number of bits decoded by tl[] and td[] */
/* inflate (decompress) the codes in a deflated (compressed) block.
   Return an error code or zero if it all goes ok. */
{
  register unsigned e;  /* table entry flag/number of extra bits */
  unsigned n;        /* length and index for copy */
  unsigned d;
  struct huft *t;       /* pointer to table entry */
  unsigned ml, md;      /* masks for bl and bd bits */
  register ulg b;       /* bit buffer */
  register unsigned k;  /* number of bits in bit buffer */

  /* make local copies of globals */
  b = pzip->bb;                       /* initialize bit buffer */
  k = pzip->bk;
  /* inflate the coded data */
  ml = mask_bits[bl];           /* precompute masks for speed */
  md = mask_bits[bd];
  for (;;)                      /* do until end of block */
  {
    NEEDBITS((unsigned)bl);
    if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)
      do {
        if (e == 99)
          return 1;
        DUMPBITS(t->b);
        e -= 16;
        NEEDBITS(e);
      } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);
    DUMPBITS(t->b);
    if (e == 16)                /* then it's a literal */
    {
      if (pzip->outbuf) {
        pzip->outbuf[pzip->outcnt] = (uch)t->v.n;
      }
      pzip->outcnt++;
    }
    else                        /* it's an EOB or a length */
    {
      /* exit if end of block */
      if (e == 15)
        break;

      /* get length of block to copy */
      NEEDBITS(e);
      n = t->v.n + ((unsigned)b & mask_bits[e]);
      DUMPBITS(e);;

      /* decode distance of block to copy */
      NEEDBITS((unsigned)bd);
      if ((e = (t = td + ((unsigned)b & md))->e) > 16)
        do {
          if (e == 99)
            return 1;
          DUMPBITS(t->b);
          e -= 16;
          NEEDBITS(e);
        } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);
      DUMPBITS(t->b);
      NEEDBITS(e);
      d = t->v.n + ((unsigned)b & mask_bits[e]);
      DUMPBITS(e);;

      while (n--) {
        if (pzip->outbuf) {
          pzip->outbuf[pzip->outcnt] = pzip->outbuf[pzip->outcnt - d];
        }
        pzip->outcnt++;
      }
    }
  }

  /* restore the globals from the locals */
  pzip->bb = b;                       /* restore global bit buffer */
  pzip->bk = k;
  /* done */
  return 0;
}

int inflate_dynamic(zip_t *pzip)
/* decompress an inflated type 2 (dynamic Huffman codes) block. */
{
  int i;                /* temporary variables */
  unsigned j;
  unsigned l;           /* last length */
  unsigned m;           /* mask for bit lengths table */
  unsigned n;           /* number of lengths to get */
  struct huft *tl;      /* literal/length code table */
  struct huft *td;      /* distance code table */
  int bl;               /* lookup bits for tl */
  int bd;               /* lookup bits for td */
  unsigned nb;          /* number of bit length codes */
  unsigned nl;          /* number of literal/length codes */
  unsigned nd;          /* number of distance codes */
  unsigned ll[286+30];  /* literal/length and distance code lengths */
  register ulg b;       /* bit buffer */
  register unsigned k;  /* number of bits in bit buffer */

  /* make local bit buffer */
  b = pzip->bb;
  k = pzip->bk;

  /* read in table lengths */
  NEEDBITS(5);
  nl = 257 + ((unsigned)b & 0x1f);      /* number of literal/length codes */
  DUMPBITS(5);
  NEEDBITS(5);
  nd = 1 + ((unsigned)b & 0x1f);        /* number of distance codes */
  DUMPBITS(5);
  NEEDBITS(4);
  nb = 4 + ((unsigned)b & 0xf);         /* number of bit length codes */
  DUMPBITS(4);
  if (nl > 286 || nd > 30)
    return 1;                   /* bad lengths */

  /* read in bit-length-code lengths */
  for (j = 0; j < nb; j++)
  {
    NEEDBITS(3);
    ll[border[j]] = (unsigned)b & 7;
    DUMPBITS(3);
  }
  for (; j < 19; j++)
    ll[border[j]] = 0;

  /* build decoding table for trees--single level, 7 bit lookup */
  bl = 7;
  if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0)
  {
    if (i == 1)
      huft_free(tl);
    return i;                   /* incomplete code set */
  }

  /* read in literal and distance code lengths */
  n = nl + nd;
  m = mask_bits[bl];
  i = l = 0;
  while ((unsigned)i < n)
  {
    NEEDBITS((unsigned)bl);
    j = (td = tl + ((unsigned)b & m))->b;
    DUMPBITS(j);
    j = td->v.n;
    if (j < 16)                 /* length of code in bits (0..15) */
      ll[i++] = l = j;          /* save last length in l */
    else if (j == 16)           /* repeat last length 3 to 6 times */
    {
      NEEDBITS(2);
      j = 3 + ((unsigned)b & 3);
      DUMPBITS(2);
      if ((unsigned)i + j > n)
        return 1;
      while (j--)
        ll[i++] = l;
    }
    else if (j == 17)           /* 3 to 10 zero length codes */
    {
      NEEDBITS(3);
      j = 3 + ((unsigned)b & 7);
      DUMPBITS(3);
      if ((unsigned)i + j > n)
        return 1;
      while (j--)
        ll[i++] = 0;
      l = 0;
    }
    else                        /* j == 18: 11 to 138 zero length codes */
    {
      NEEDBITS(7);
      j = 11 + ((unsigned)b & 0x7f);
      DUMPBITS(7);
      if ((unsigned)i + j > n)
        return 1;
      while (j--)
        ll[i++] = 0;
      l = 0;
    }
  }

  /* free decoding table for trees */
  huft_free(tl);

  /* restore the global bit buffer */
  pzip->bb = b;
  pzip->bk = k;

  /* build the decoding tables for literal/length and distance codes */
  bl = lbits;
  if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0)
  {
    if (i == 1) {
      huft_free(tl);
    }
    return i;                   /* incomplete code set */
  }
  bd = dbits;
  if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0)
  {
    if (i == 1) {
#ifdef PKZIP_BUG_WORKAROUND
      i = 0;
    }
#else
      huft_free(td);
    }
    huft_free(tl);
    return i;                   /* incomplete code set */
#endif
  }

  /* decompress until an end-of-block code */
  if (inflate_codes(pzip, tl, td, bl, bd))
    return 1;

  /* free the decoding tables, return */
  huft_free(tl);
  huft_free(td);
  return 0;
}

int inflate_stored(zip_t *pzip)
/* "decompress" an inflated type 0 (stored) block. */
{
  unsigned n;           /* number of bytes in block */
  unsigned w;           /* current window position */
  register ulg b;       /* bit buffer */
  register unsigned k;  /* number of bits in bit buffer */


  /* make local copies of globals */
  b = pzip->bb;                       /* initialize bit buffer */
  k = pzip->bk;


  /* go to byte boundary */
  n = k & 7;
  DUMPBITS(n);


  /* get the length and its complement */
  NEEDBITS(16);
  n = ((unsigned)b & 0xffff);
  DUMPBITS(16);
  NEEDBITS(16);
  if (n != (unsigned)((~b) & 0xffff))
    return 1;                   /* error in compressed data */
  DUMPBITS(16);


  /* read and output the compressed data */
  while (n--)
  {
    NEEDBITS(8);
    if(pzip->outbuf)
    {
        pzip->outbuf[pzip->outcnt] = (uch)b;
    }
    pzip->outcnt++;

    DUMPBITS(8);
  }


  /* restore the globals from the locals */
  pzip->bb = b;                       /* restore global bit buffer */
  pzip->bk = k;
  return 0;
}


int inflate_fixed(zip_t * pzip)
/* decompress an inflated type 1 (fixed Huffman codes) block.  We should
   either replace this with a custom decoder, or at least precompute the
   Huffman tables. */
{
  int i;                /* temporary variable */
  struct huft *tl;      /* literal/length code table */
  struct huft *td;      /* distance code table */
  int bl;               /* lookup bits for tl */
  int bd;               /* lookup bits for td */
  unsigned l[288];      /* length list for huft_build */


  /* set up literal table */
  for (i = 0; i < 144; i++)
    l[i] = 8;
  for (; i < 256; i++)
    l[i] = 9;
  for (; i < 280; i++)
    l[i] = 7;
  for (; i < 288; i++)          /* make a complete, but wrong code set */
    l[i] = 8;
  bl = 7;
  if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0)
    return i;


  /* set up distance table */
  for (i = 0; i < 30; i++)      /* make an incomplete code set */
    l[i] = 5;
  bd = 5;
  if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1)
  {
    huft_free(tl);
    return i;
  }


  /* decompress until an end-of-block code */
  if (inflate_codes(pzip, tl, td, bl, bd))
    return 1;


  /* free the decoding tables, return */
  huft_free(tl);
  huft_free(td);
  return 0;
}


int inflate_block(zip_t *pzip, int *e)
{
  unsigned t;           /* block type */
  register ulg b;       /* bit buffer */
  register unsigned k;  /* number of bits in bit buffer */

  /* make local bit buffer */
  b = pzip->bb;
  k = pzip->bk;
	
  /* read in last block bit */
  NEEDBITS(1);
  *e = (int)b & 1;
  DUMPBITS(1);

  /* read in block type */
  NEEDBITS(2);
  t = (unsigned)b & 3;
  DUMPBITS(2);

  /* restore the global bit buffer */
  pzip->bb = b;
  pzip->bk = k;
  
  printf("t:[%d]\n", t);
  /* inflate that block type */
  if (t == 2)
  {
    return inflate_dynamic(pzip);
  }
  
  if (t == 0)
  {
    return inflate_stored(pzip);
  }
  
  if(t == 1)
  {
  	return inflate_fixed(pzip);
  }
  /* bad block type */
  return 0;
}

int inflate(zip_t *pzip)
{
    int e;                /* last block flag */
    int r;                /* result code */

    pzip->bb = 0;
    pzip->bk = 0;
    pzip->outcnt = 0;
                /* initialize window, bit buffer */
    /* decompress until the last block */
    do 
    {
      if((r = inflate_block(pzip, &e))!= 0)
      {
        return r;
      }
    } while (!e);

    return 0;
}

int unzip(zip_t *pzip, char *path, cfilename_t *cFileName)
{
    int iFileNameCount = 0;
    unsigned char zipsignature[] = { 0x50, 0x4b, 3, 4 };
    uch *p = NULL;
    uch *beg;
    uch *ptop;
    int siz = pzip->inbufsiz;
    int pathlen = path?strlen(path) : 0;
    
    beg = pzip->inbuf;
    ptop = beg + siz;

    //while((NULL != (p = (uch *)(long)memmem(beg, siz, (void *)zipsignature, 4))))
    while((NULL != (p = (uch *)(long)memmem(beg, siz, (void *)zipsignature, 4))))
    {

      int filenamlen;
      unsigned char *pos;
      pos = p + ZIP_FILENAME_LENGTH_OFFSET;
      filenamlen = pos[0] | (pos[1] << 8);
      pos += ZIP_FILENAME_OFFSET - ZIP_FILENAME_LENGTH_OFFSET;

      if (NULL == path) 
      {
	      printf("p:[%x]\n", p[0]);
	      
        char buf[100];
        char *rsp = NULL;
        memset(buf, 0x00, sizeof(buf));
        rsp = malloc(sizeof(char) * 100);
        sprintf(rsp, "%.*s\n", filenamlen, pos);
        memset(cFileName->filnamesave[iFileNameCount], 0x00, 100);
        strcpy(buf, rsp);
        memcpy(cFileName->filnamesave[iFileNameCount], buf, strlen(buf)-1);
        printf("cFileName->filnamesave[iFileNameCount]:[%s]\n", cFileName->filnamesave[iFileNameCount]);
        iFileNameCount++;
        free(rsp);
        
      } else if (pathlen == filenamlen && !memcmp(path, (char *)pos, filenamlen)) 
      {
      	
        pzip->inptr = (int)(pos - pzip->inbuf) + filenamlen;
        int ret = inflate(pzip);
      }
      beg = pos + filenamlen;
      siz = ptop - beg;
    }
    
    return iFileNameCount;
}
#endif
//---------------------------------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int iCount = 0;              //total file in zip file
    char *file_path_getcwd;      //get the current path
    char curFilePath[100];      //the current path
    char tmpFilePath[100];      //save the total temp path
    char tmpBuffer[100];        //save the temp file path
    

    
    if (2 <= argc)
    {
      zip_t  zip;
      cfilename_t cfilename;
      
      #if 1
      if (0 > load_zip_file(argv[1])) 
      {
        return -1;
      }
      #endif
      
      bzero(&zip, sizeof(zip_t));
      bzero(&cfilename, sizeof(cfilename));
      
      zip.inbuf = start;
      zip.inbufsiz = zipfilelength;
      
      //0. get current dir
	    memset(curFilePath, 0x00, sizeof(curFilePath));
	    file_path_getcwd=(char *)malloc(FILEPATH_MAX);
	    getcwd(file_path_getcwd,FILEPATH_MAX);
	    strcpy(curFilePath, file_path_getcwd);
	    free(file_path_getcwd);
	    strcat(curFilePath, "/");    //Get the Current Dir
	    chdir(curFilePath);          //Enter the Current dir
	    
      //1. get filename
      iCount = unzip(&zip, NULL, &cfilename);
      
      //---------------------------------create floder start
      for(int i = 0; i < iCount; i++)
      {
          memset(tmpFilePath, 0x00, sizeof(tmpFilePath));
          
          //Get Total file path
          strcpy(tmpFilePath, curFilePath);
          strcat(tmpFilePath, cfilename.filnamesave[i]);
          
          //Get File path length
          int cfilenamelen = strlen(tmpFilePath);
          
          //Analys file path and create the floder and create file
          for(int i = 0; i < cfilenamelen; i++)
          {
              if(tmpFilePath[i] == '/' && i != 0 && tmpFilePath[cfilenamelen-1] == '/')
              {
                  memset(tmpBuffer, 0x00, sizeof(tmpBuffer));
                  memcpy(tmpBuffer, tmpFilePath, i+1);
                  if(!(access(tmpBuffer,F_OK) == 0))
                  {
                    int ret = mkdir(tmpBuffer, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
                    if(ret < 0)
                    {
                      return -1;
                    }
                  }
              }
          }
        }
      //---------------------------------create floder end    
      
      //---------------------------------create file and write data start
     		printf("iCount:[%d]\n", iCount);
	      for(int i = 0; i < iCount; i++)
	      {
	          memset(tmpFilePath, 0x00, sizeof(tmpFilePath));
	          bzero(&zip, sizeof(zip_t));
	          zip.inbuf = start;
	          zip.inbufsiz = zipfilelength;
	          
	          //Get Total file path
	          strcpy(tmpFilePath, curFilePath);
	          strcat(tmpFilePath, cfilename.filnamesave[i]);
	          
	          //Get File path length
	          int cfilenamelen = strlen(tmpFilePath);
	          
	          //Create file and write data
	          //filename:tmpFilePath, filedata_len:cfilenamelen
	          //
	          if(tmpFilePath[cfilenamelen-1] == '/')
	          {
	          		
	          		printf("filnamesave:[%s]\n", cfilename.filnamesave[i]);
	          }
	          else if(tmpFilePath[cfilenamelen-1] != '/')
	          {
	            unzip(&zip, cfilename.filnamesave[i], &cfilename);
	            zip.outbuf = malloc(zip.outcnt);
	            unzip(&zip, cfilename.filnamesave[i], &cfilename);
	            
	            
	            
	            int need_to_write = 0;
	            need_to_write = zip.outcnt;
	            if(need_to_write == 0)
	            {
	            		large_little_flag = 1;
	            }
	            
	            char filename_buf[50];
	        		int ibufCount = 0;
	        		memset(filename_buf, 0x00, sizeof(filename_buf));
	        		for(ibufCount = strlen(cfilename.filnamesave[i]); ibufCount >= 0; ibufCount--)
	        		{
	        				if(cfilename.filnamesave[i][ibufCount] == '/')
	        				{
	        					break;
	        				}
	        				
	        		}
	
	        		memcpy(filename_buf, cfilename.filnamesave[i]+ibufCount+1, strlen(cfilename.filnamesave[i]) - ibufCount);
	            printf("filnamesave:[%s]-[%s], need_to_write:[%d]\n", cfilename.filnamesave[i], filename_buf, need_to_write);
	            
	            int outfd = 0;
	
	          if(!(access(tmpFilePath,F_OK) == 0))
	          {
	              outfd = creat(tmpFilePath,S_IWRITE|S_IREAD);
	              if (outfd < 1)
	              { 
	                return -1;    
	              } 
	              close(outfd);
	              outfd = open(tmpFilePath, O_CREAT|O_RDWR, 0664);
	              int len_write_in = 0;
	              int ret = 0;
	              #if 0
	              while(need_to_write > 0)
	              {
	                if(need_to_write > MAX_WRITE_SIZE)
	                {
	                  len_write_in = MAX_WRITE_SIZE;
	                }
	                else
	                {
	                  len_write_in = need_to_write;
	                }
	                ret = write(outfd,zip.outbuf,len_write_in);
	                need_to_write -= ret;
	              }
	              #else
	              ret = write(outfd,zip.outbuf,zip.outcnt);
	              #endif
	              close(outfd);
	            }
	            else
	            {
	                outfd = open(tmpFilePath, O_CREAT|O_RDWR, 0664);
	                int len_write_in = 0;
	                int ret = 0;
	                #if 0
	                while(need_to_write > 0)
	                {
	                  if(need_to_write > MAX_WRITE_SIZE)
	                  {
	                    len_write_in = MAX_WRITE_SIZE;
	                  }
	                  else
	                  {
	                    len_write_in = need_to_write;
	                  }
	                  ret = write(outfd,zip.outbuf,len_write_in);
	                  need_to_write -= ret;
	                }
	                #else
	                ret = write(outfd,zip.outbuf,zip.outcnt);
	                #endif
	                close(outfd);
	            }
	            
	            
	          }
	          else
	          {
	          	continue;
	          }
	      }
      printf("End\n");
    }
}

#if 1
int load_zip_file(char *path)
{
	int fd = -1;
	struct stat f_stat;

	if ((fd = open(path, O_RDONLY)) == -1)
		return -1;
	if (fstat(fd, &f_stat))
		return -1;

	zipfilelength = (int)f_stat.st_size;
	
	printf("zipfilelength:[%d]\n", zipfilelength);
	


	char *start_buffer = NULL;
	start_buffer = malloc(zipfilelength);
	
	int ret = read(fd, start_buffer, zipfilelength);
	start = start_buffer;

	
	close(fd);
	return 0;
}

#endif

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值