home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_100 / 154_01 / uniq2.c < prev    next >
Text File  |  1979-12-31  |  2KB  |  85 lines

  1. /* uniq2.c:    filters-out ALL repeated lines (keeps 1st occurrence) -
  2.  
  3. ------
  4.     (c) Chuck Allison  May 1985
  5. ------
  6.  
  7. */
  8.  
  9. #include <stdio.h>
  10. #define MAXWIDTH 256
  11. #define MAXLINES 500
  12. #define MAXFILES 150
  13.  
  14. main(argc,argv)
  15. int argc;
  16. char *argv[];
  17. {
  18.     int i, maxarg = MAXFILES, xargc;
  19.     char *xargv[MAXFILES];
  20.     FILE *f;
  21.  
  22.     if (argc == 1)
  23.         uniq(stdin);
  24.     else
  25.     {
  26.         /* expand filespecs (Mark Williams C only!).. */
  27.         xargc = exargs("files",argc,argv,xargv,maxarg);
  28.  
  29.         for (i = 0; i < xargc; ++i)
  30.             if ((f = fopen(xargv[i],"r")) == NULL)
  31.             {
  32.                 printf("can't open: \"%s\"\n",xargv[i]);
  33.                 exit(1);
  34.             } 
  35.             else
  36.             {
  37.                 uniq(f);
  38.                 fclose(f);
  39.             }
  40.     }
  41. }
  42.  
  43. uniq(f)
  44. FILE *f;
  45. {
  46.     int i, n, j, temp, idx[MAXLINES], mark[MAXLINES];
  47.     char *a[MAXLINES], s[MAXWIDTH];
  48.  
  49.     /* ..read lines into memory.. */
  50.     for (n = 0; fgets(s,MAXWIDTH-1,f) != NULL; ++n)
  51.     {
  52.         a[n] = (char *) malloc(strlen(s)+1);
  53.         if (a[n] == NULL || n == MAXLINES)
  54.         {
  55.             printf(stderr,"memory failure\n");
  56.             exit(1);
  57.         }
  58.         strcpy(a[n],s);
  59.         idx[n] = n;        /* ..identity map for indices.. */
  60.         mark[n] = 0;    /* ..initialize line as unmarked.. */
  61.     }
  62.  
  63.     /* ..sort with indices (must use a stable algorithm).. */
  64.     for (i = n-2; i >= 0; --i)
  65.         for (j = i+1; j < n; ++j)
  66.         {
  67.             if (strcmp(a[idx[j-1]],a[idx[j]]) <= 0)
  68.                 break;
  69.             temp = idx[j];
  70.             idx[j] = idx[j-1];
  71.             idx[j-1] = temp;
  72.         }
  73.  
  74.     /* ..mark duplicates.. */
  75.     for (i = 1; i < n; ++i)
  76.         if (strcmp(a[idx[i-1]],a[idx[i]]) == 0)
  77.             mark[idx[i]] = 1;
  78.  
  79.     /* ..print unmarked lines.. */
  80.     for (i = 0; i < n; ++i)
  81.         if (!mark[i])
  82.             fputs(a[i],stdout);
  83. }
  84.  
  85.