⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 zip.c

📁 给出了 zip 压缩算法的完整实现过程。
💻 C
📖 第 1 页 / 共 5 页
字号:
#ifndef USE_ZIPMAINint main(argc, argv)#elseint zipmain(argc, argv)#endifint argc;               /* number of tokens in command line */char **argv;            /* command line tokens *//* Add, update, freshen, or delete zip entries in a zip file.  See the   command help in help() above. */{  int a;                /* attributes of zip file */  ulg c;                /* start of central directory */  int d;                /* true if just adding to a zip file */  char *e;              /* malloc'd comment buffer */  struct flist far *f;  /* steps through found linked list */  int i;                /* arg counter, root directory flag */  int k;                /* next argument type, marked counter,                           comment size, entry count */  ulg n;                /* total of entry len's */  int o;                /* true if there were any ZE_OPEN errors */  char *p;              /* steps through option arguments */  char *pp;             /* temporary pointer */  ulg *cmptime = NULL;  /* pointer to 'before' or 'after' */  int r;                /* temporary variable */  int s;                /* flag to read names from stdin */  ulg t;                /* file time, length of central directory */  int first_listarg = 0;/* index of first arg of "process these files" list */  struct zlist far *v;  /* temporary variable */  struct zlist far * far *w;    /* pointer to last link in zfiles list */  FILE *x, *y;          /* input and output zip files */  struct zlist far *z;  /* steps through zfiles linked list */  int bad_open_is_error = 0; /* if open read fails, 0=warning, 1=error */#ifdef WINDLL  int retcode;          /* return code for dll */#endif#if (!defined(VMS) && !defined(CMS_MVS))  char *zipbuf;         /* stdio buffer for the zip file */#endif /* !VMS && !CMS_MVS */  FILE *comment_stream; /* set to stderr if anything is read from stdin */#ifdef THEOS  /* the argument expansion from the standard library is full of bugs */  /* use mine instead */  _setargv(&argc, &argv);  setlocale(LC_CTYPE,"I");#else  SETLOCALE(LC_CTYPE,"");#endif#if defined(__IBMC__) && defined(__DEBUG_ALLOC__)  {    extern void DebugMalloc(void);    atexit(DebugMalloc);  }#endif#ifdef QDOS  {    extern void QDOSexit(void);    atexit(QDOSexit);  }#endif#ifdef RISCOS  set_prefix();#endif#ifdef __human68k__  fflush(stderr);  setbuf(stderr, NULL);#endif/* Re-initialize global variables to make the zip dll re-entrant. It is * possible that we could get away with not re-initializing all of these * but better safe than sorry. */#if defined(MACOS) || defined(WINDLL)  action = ADD; /* one of ADD, UPDATE, FRESHEN, or DELETE */  comadd = 0;   /* 1=add comments for new files */  zipedit = 0;  /* 1=edit zip comment and all file comments */  latest = 0;   /* 1=set zip file time to time of latest file */  before = 0;   /* 0=ignore, else exclude files before this time */  after = 0;    /* 0=ignore, else exclude files newer than this time */  test = 0;     /* 1=test zip file with unzip -t */  tempdir = 0;  /* 1=use temp directory (-b) */  junk_sfx = 0; /* 1=junk the sfx prefix */#if defined(AMIGA) || defined(MACOS)  filenotes = 0;/* 1=take comments from AmigaDOS/MACOS filenotes */#endif  zipstate = -1;  tempzip = NULL;  fcount = 0;  recurse = 0;         /* 1=recurse into directories; 2=match filenames */  dispose = 0;         /* 1=remove files after put in zip file */  pathput = 1;         /* 1=store path with name */  method = BEST;       /* one of BEST, DEFLATE (only), or STORE (only) */  dosify = 0;          /* 1=make new entries look like MSDOS */  verbose = 0;         /* 1=report oddities in zip file structure */  fix = 0;             /* 1=fix the zip file */  adjust = 0;          /* 1=adjust offsets for sfx'd file (keep preamble) */  level = 6;           /* 0=fastest compression, 9=best compression */  translate_eol = 0;   /* Translate end-of-line LF -> CR LF */#if defined(OS2) || defined(WIN32)  use_longname_ea = 0; /* 1=use the .LONGNAME EA as the file's name */#endif#ifdef NTSD_EAS  use_privileges = 0;  /* 1=use security privileges overrides */#endif  hidden_files = 0;    /* process hidden and system files */  volume_label = 0;    /* add volume label */  dirnames = 1;        /* include directory entries by default */  linkput = 0;         /* 1=store symbolic links as such */  noisy = 1;           /* 0=quiet operation */  extra_fields = 1;    /* 0=do not create extra fields */  special = ".Z:.zip:.zoo:.arc:.lzh:.arj"; /* List of special suffixes */  key = NULL;          /* Scramble password if scrambling */  tempath = NULL;      /* Path for temporary files */  found = NULL;        /* where in found, or new found entry */  fnxt = &found;  patterns = NULL;     /* List of patterns to be matched */  pcount = 0;          /* number of patterns */  icount = 0;          /* number of include only patterns */  Rcount = 0;          /* number of -R include patterns */  bad_open_is_error = 0; /* if read fails, 0=warning, 1=error */#ifndef MACOS  retcode = setjmp(zipdll_error_return);  if (retcode) {    return retcode;  }#endif /* !MACOS */#endif /* MACOS || WINDLL */  mesg = (FILE *) stdout; /* cannot be made at link time for VMS */  comment_stream = (FILE *)stdin;  init_upper();           /* build case map table */#if (defined(WIN32) && defined(USE_EF_UT_TIME))  /* For the Win32 environment, we may have to "prepare" the environment     prior to the tzset() call, to work around tzset() implementation bugs.   */  iz_w32_prepareTZenv();#endif#if (defined(IZ_CHECK_TZ) && defined(USE_EF_UT_TIME))#  ifndef VALID_TIMEZONE#     define VALID_TIMEZONE(tmp) \             (((tmp = getenv("TZ")) != NULL) && (*tmp != '\0'))#  endif  zp_tz_is_valid = VALID_TIMEZONE(p);#if (defined(AMIGA) || defined(DOS))  if (!zp_tz_is_valid)    extra_fields = 0;     /* disable storing "UT" time stamps */#endif /* AMIGA || DOS */#endif /* IZ_CHECK_TZ && USE_EF_UT_TIME *//* For systems that do not have tzset() but supply this function using another   name (_tzset() or something similar), an appropiate "#define tzset ..."   should be added to the system specifc configuration section.  */#if (!defined(TOPS20) && !defined(VMS))#if (!defined(RISCOS) && !defined(MACOS) && !defined(QDOS))#if (!defined(BSD) && !defined(MTS) && !defined(CMS_MVS) && !defined(TANDEM))  tzset();#endif#endif#endif#ifdef VMSCLI    {        ulg status = vms_zip_cmdline(&argc, &argv);        if (!(status & 1))            return status;    }#endif /* VMSCLI */  /* extract extended argument list from environment */  expand_args(&argc, &argv);#ifndef WINDLL  /* Process arguments */  diag("processing arguments");  /* First, check if just the help or version screen should be displayed */  if (argc == 1 && isatty(1))   /* no arguments, and output screen available */  {                             /* show help screen */#ifdef VMSCLI    VMSCLI_help();#else    help();#endif    EXIT(ZE_OK);  }  else if (argc == 2 && strcmp(argv[1], "-v") == 0 &&           /* only "-v" as argument, and */           (isatty(1) || isatty(0)))           /* stdout or stdin is connected to console device */  {                             /* show diagnostic version info */    version_info();    EXIT(ZE_OK);  }#ifndef VMS#  ifndef RISCOS  envargs(&argc, &argv, "ZIPOPT", "ZIP");  /* get options from environment */#  else /* RISCOS */  envargs(&argc, &argv, "ZIPOPT", "Zip$Options");  /* get options from environment */  getRISCOSexts("Zip$Exts");        /* get the extensions to swap from environment */#  endif /* ? RISCOS */#else /* VMS */  envargs(&argc, &argv, "ZIPOPT", "ZIP_OPTS");  /* 4th arg for unzip compat. */#endif /* ?VMS */#endif /* !WINDLL */  zipfile = tempzip = NULL;  tempzf = NULL;  d = 0;                        /* disallow adding to a zip file */#if (!defined(MACOS) && !defined(WINDLL))   signal(SIGINT, handler);# ifdef SIGTERM                  /* AMIGADOS and others have no SIGTERM */   signal(SIGTERM, handler);# endif# if defined(SIGABRT) && !(defined(AMIGA) && defined(__SASC))   signal(SIGABRT, handler);# endif# ifdef SIGBREAK   signal(SIGBREAK, handler);# endif# ifdef SIGBUS   signal(SIGBUS, handler);# endif# ifdef SIGILL   signal(SIGILL, handler);# endif# ifdef SIGSEGV   signal(SIGSEGV, handler);# endif#endif /* !MACOS && !WINDLL */  k = 0;                        /* Next non-option argument type */  s = 0;                        /* set by -@ if -@ is early */  r = get_filters(argc, argv);      /* scan first the -x and -i patterns */#ifdef WINDLL  if (r != ZE_OK)    return r;#endif  for (i = 1; i < argc; i++)  {    if (argv[i][0] == '-')    {      if (argv[i][1])        for (p = argv[i]+1; *p; p++)          switch (*p)          {#ifdef EBCDIC            case 'a':              aflag = ASCII;              printf("Translating to ASCII...\n");              break;#endif /* EBCDIC */#ifdef CMS_MVS            case 'B':              bflag = 1;              printf("Using binary mode...\n");              break;#endif /* CMS_MVS */#ifdef TANDEM            case 'B':              nskformatopt(&p);              break;#endif            case '0':              method = STORE; level = 0; break;            case '1':  case '2':  case '3':  case '4':            case '5':  case '6':  case '7':  case '8':  case '9':                        /* Set the compression efficacy */              level = *p - '0';  break;            case 'A':   /* Adjust unzipsfx'd zipfile:  adjust offsets only */              adjust = 1; break;            case 'b':   /* Specify path for temporary file */              tempdir = 1;              if (k != 0) {                ZIPERR(ZE_PARMS, "use -b before zip file name");              }              else                k = 1;          /* Next non-option is path */              break;            case 'c':   /* Add comments for new files in zip file */              comadd = 1;  break;            case 'd':   /* Delete files from zip file */#ifdef MACOS              if (p[1] == 'f') {                ++p;                MacZip.DataForkOnly = true;              } else#endif /* MACOS */              {                if (action != ADD) {                  ZIPERR(ZE_PARMS, "specify just one action");                }                action = DELETE;                break;              }            case 'D':   /* Do not add directory entries */              dirnames = 0; break;            case 'e':   /* Encrypt */#if !CRYPT              ZIPERR(ZE_PARMS, "encryption not supported");#else /* CRYPT */              if (key == NULL) {                if ((key = malloc(IZ_PWLEN+1)) == NULL) {                  ZIPERR(ZE_MEM, "was getting encryption password");                }                r = encr_passwd(ZP_PW_ENTER, key, IZ_PWLEN+1, zipfile);                if (r != IZ_PW_ENTERED) {                  if (r < IZ_PW_ENTERED)                    r = ZE_PARMS;                  ZIPERR(r, "was getting encryption password");                }                if (*key == '\0') {                  ZIPERR(ZE_PARMS, "zero length password not allowed");                }                if ((e = malloc(IZ_PWLEN+1)) == NULL) {                  ZIPERR(ZE_MEM, "was verifying encryption password");                }                r = encr_passwd(ZP_PW_VERIFY, e, IZ_PWLEN+1, zipfile);                if (r != IZ_PW_ENTERED && r != IZ_PW_SKIPVERIFY) {                  free((zvoid *)e);                  if (r < ZE_OK) r = ZE_PARMS;                  ZIPERR(r, "was verifying encryption password");                }                r = ((r == IZ_PW_SKIPVERIFY) ? 0 : strcmp(key, e));                free((zvoid *)e);                if (r) {                  ZIPERR(ZE_PARMS, "password verification failed");                }              }#endif /* !CRYPT */              break;            case 'F':   /* fix the zip file */              fix++; break;            case 'f':   /* Freshen zip file--overwrite only */              if (action != ADD) {                ZIPERR(ZE_PARMS, "specify just one action");              }              action = FRESHEN;              break;            case 'g':   /* Allow appending to a zip file */              d = 1;  break;#ifndef WINDLL            case 'h': case 'H': case '?':  /* Help */#ifdef VMSCLI              VMSCLI_help();#else              help();#endif              RETURN(finish(ZE_OK));#endif /* !WINDLL */#ifdef RISCOS            case 'I':   /* Don't scan through Image files */              scanimage = 0;              break;#endif#ifdef MACOS            case 'j':   /* Junk path / Store absolute path */              if (p[1] == 'j') {    /* store absolute path including volname */                ++p;                MacZip.StoreFullPath = true;              } else {              /* junk directory names */                pathput = 0;  break;              }#else /* !MACOS */            case 'j':   /* Junk directory names */              pathput = 0;  break;#endif /* ?MACOS */            case 'J':   /* Junk sfx prefix */              junk_sfx = 1;  break;            case 'k':   /* Make entries using DOS names (k for Katz) */              dosify = 1;  break;            case 'l':   /* Translate end-of-line */              translate_eol++; break;#ifndef WINDLL            case 'L':   /* Show license */              license();              RETURN(finish(ZE_OK));#endif            case 'm':   /* Delete files added or updated in zip file */              dispose++;              if (dispose == 2)                ZIPERR(ZE_PARMS, "mm not supported");              break;            case 'M':   /* Read failures (misses) are errors instead of warnings */              bad_open_is_error++;              break;            case 'n':   /* Don't compress files with a special suffix */              special = NULL; /* will be set at next argument */              break;#if defined(AMIGA) || defined(MACOS)            case 'N':   /* Get zipfile comments from AmigaDOS/MACOS filenotes */              filenotes = 1; break;#endif            case 'o':   /* Set zip file time to time of latest file in it */              latest = 1;  break;            case 'p':   /* Store path with name */              break;            /* (do nothing as annoyance avoidance) */            case 'P':   /* password for encryption */              if (k != 0) {                ZIPERR(ZE_PARMS, "use -P before zip file name");              }              if (key != NULL) {                ZIPERR(ZE_PARMS, "can only have one -P");              }#if CRYPT              k = 7;#else              ZIPERR(ZE_PARMS, "encryption not supported");#endif /* CRYPT */              break;#if defined(QDOS) || defined(QLZIP)            case 'Q':              qlflag  = strtol((p+1), &p, 10);              if (qlflag == 0) qlflag = 4;              p--;              break;#endif            case 'q':   /* Quiet operation */              noisy = 0;#ifdef MACOS              MacZip.MacZip_Noisy = false;#endif  /* MACOS */              if (verbose) verbose--;              break;            case 'r':   /* Recurse into subdirectories, match full path */              if (recurse == 2) {                ZIPERR(ZE_PARMS, "do not specify both -r and -R");              }              recurse = 1;  break;            case 'R':   /* Recurse into subdirectories, match filename */              if (recurse == 1) {                ZIPERR(ZE_PARMS, "do not specify both -r and -R");

⌨️ 快捷键说明

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