home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 1 / FFMCD01.bin / useful / dist / gnu / textutils / textutils-1.6-amiga / src / join.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-15  |  14.2 KB  |  702 lines

  1. /* join - join lines of two files on a common field
  2.    Copyright (C) 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written by Mike Haertel, mike@gnu.ai.mit.edu. */
  19.  
  20. /* Get isblank from GNU libc.  */
  21. #define _GNU_SOURCE
  22.  
  23. #include <stdio.h>
  24. #include <sys/types.h>
  25. #include <getopt.h>
  26. #include "system.h"
  27. #include "version.h"
  28.  
  29. char *xmalloc ();
  30. char *xrealloc ();
  31. void error ();
  32. static void usage ();
  33.  
  34. #define min(A, B) ((A) < (B) ? (A) : (B))
  35.  
  36. /* An element of the list describing the format of each
  37.    output line. */
  38. struct outlist
  39. {
  40.   int file;            /* File to take field from (1 or 2). */
  41.   int field;            /* Field number to print. */
  42.   struct outlist *next;
  43. };
  44.  
  45. /* A field of a line. */
  46. struct field
  47. {
  48.   char *beg;            /* First character in field. */
  49.   char *lim;            /* Character after last character in field. */
  50. };
  51.  
  52. /* A line read from an input file.  Newlines are not stored. */
  53. struct line
  54. {
  55.   char *beg;            /* First character in line. */
  56.   char *lim;            /* Character after last character in line. */
  57.   int nfields;            /* Number of elements in `fields'. */
  58.   struct field *fields;
  59. };
  60.  
  61. /* One or more consecutive lines read from a file that all have the
  62.    same join field value. */
  63. struct seq
  64. {
  65.   int count;            /* Elements used in `lines'. */
  66.   int alloc;            /* Elements allocated in `lines'. */
  67.   struct line *lines;
  68. };
  69.  
  70. /* The name this program was run with. */
  71. char *program_name;
  72.  
  73. /* If nonzero, print unpairable lines in file 1 or 2. */
  74. static int print_unpairables_1, print_unpairables_2;
  75.  
  76. /* If nonzero, print pairable lines. */
  77. static int print_pairables;
  78.  
  79. /* Empty output field filler. */
  80. static char *empty_filler;
  81.  
  82. /* Field to join on. */
  83. static int join_field_1, join_field_2;
  84.  
  85. /* List of fields to print. */
  86. static struct outlist *outlist;
  87.  
  88. /* Last element in `outlist', where a new element can be added. */
  89. static struct outlist *outlist_end;
  90.  
  91. /* Tab character separating fields; if this is NUL fields are separated
  92.    by any nonempty string of white space, otherwise by exactly one
  93.    tab character. */
  94. static char tab;
  95.  
  96. /* If non-zero, display usage information and exit.  */
  97. static int flag_help;
  98.  
  99. /* If non-zero, print the version on standard error.  */
  100. static int flag_version;
  101.  
  102. /* When using getopt_long_only, no long option can start with
  103.    a character that is a short option. */
  104. static struct option const longopts[] =
  105. {
  106.   {"j", required_argument, NULL, 'j'},
  107.   {"j1", required_argument, NULL, '1'},
  108.   {"j2", required_argument, NULL, '2'},
  109.   {"help", no_argument, &flag_help, 1},
  110.   {"version", no_argument, &flag_version, 1},
  111.   {NULL, 0, NULL, 0}
  112. };
  113.  
  114. /* Fill in the `fields' structure in LINE. */
  115.  
  116. static void
  117. xfields (line)
  118.      struct line *line;
  119. {
  120.   static int nfields = 2;
  121.   int i;
  122.   register char *ptr, *lim;
  123.  
  124.   line->fields = (struct field *) xmalloc (nfields * sizeof (struct field));
  125.  
  126.   ptr = line->beg;
  127.   lim = line->lim;
  128.  
  129.   for (i = 0; ptr < lim; ++i)
  130.     {
  131.       if (i == nfields)
  132.     {
  133.       nfields *= 2;
  134.       line->fields = (struct field *)
  135.         xrealloc ((char *) line->fields, nfields * sizeof (struct field));
  136.     }
  137.       if (tab)
  138.     {
  139.       line->fields[i].beg = ptr;
  140.       while (ptr < lim && *ptr != tab)
  141.         ++ptr;
  142.       line->fields[i].lim = ptr;
  143.       if (ptr < lim)
  144.         ++ptr;
  145.     }
  146.       else
  147.     {
  148.       line->fields[i].beg = ptr;
  149.       while (ptr < lim && !ISSPACE (*ptr))
  150.         ++ptr;
  151.       line->fields[i].lim = ptr;
  152.       while (ptr < lim && ISSPACE (*ptr))
  153.         ++ptr;
  154.     }
  155.     }
  156.  
  157.   line->nfields = i;
  158. }
  159.  
  160. /* Read a line from FP into LINE and split it into fields.
  161.    Return 0 if EOF, 1 otherwise. */
  162.  
  163. static int
  164. get_line (fp, line)
  165.      FILE *fp;
  166.      struct line *line;
  167. {
  168.   static int linesize = 80;
  169.   int c, i;
  170.   char *ptr;
  171.  
  172.   if (feof (fp))
  173.     return 0;
  174.  
  175.   ptr = xmalloc (linesize);
  176.  
  177.   for (i = 0; (c = getc (fp)) != EOF && c != '\n'; ++i)
  178.     {
  179.       if (i == linesize)
  180.     {
  181.       linesize *= 2;
  182.       ptr = xrealloc (ptr, linesize);
  183.     }
  184.       ptr[i] = c;
  185.     }
  186.  
  187.   if (c == EOF && i == 0)
  188.     {
  189.       free (ptr);
  190.       return 0;
  191.     }
  192.  
  193.   line->beg = ptr;
  194.   line->lim = line->beg + i;
  195.   xfields (line);
  196.   return 1;
  197. }
  198.  
  199. static void
  200. freeline (line)
  201.      struct line *line;
  202. {
  203.   free ((char *) line->fields);
  204.   free (line->beg);
  205. }
  206.  
  207. static void
  208. initseq (seq)
  209.      struct seq *seq;
  210. {
  211.   seq->count = 0;
  212.   seq->alloc = 1;
  213.   seq->lines = (struct line *) xmalloc (seq->alloc * sizeof (struct line));
  214. }
  215.  
  216. /* Read a line from FP and add it to SEQ.  Return 0 if EOF, 1 otherwise. */
  217.  
  218. static int
  219. getseq (fp, seq)
  220.      FILE *fp;
  221.      struct seq *seq;
  222. {
  223.   if (seq->count == seq->alloc)
  224.     {
  225.       seq->alloc *= 2;
  226.       seq->lines = (struct line *)
  227.     xrealloc ((char *) seq->lines, seq->alloc * sizeof (struct line));
  228.     }
  229.  
  230.   if (get_line (fp, &seq->lines[seq->count]))
  231.     {
  232.       ++seq->count;
  233.       return 1;
  234.     }
  235.   return 0;
  236. }
  237.  
  238. static void
  239. delseq (seq)
  240.      struct seq *seq;
  241. {
  242.   free ((char *) seq->lines);
  243. }
  244.  
  245. /* Return <0 if the join field in LINE1 compares less than the one in LINE2;
  246.    >0 if it compares greater; 0 if it compares equal. */
  247.  
  248. static int
  249. keycmp (line1, line2)
  250.      struct line *line1;
  251.      struct line *line2;
  252. {
  253.   char *beg1, *beg2;        /* Start of field to compare in each file. */
  254.   int len1, len2;        /* Length of fields to compare. */
  255.   int diff;
  256.  
  257.   if (join_field_1 < line1->nfields)
  258.     {
  259.       beg1 = line1->fields[join_field_1].beg;
  260.       len1 = line1->fields[join_field_1].lim
  261.     - line1->fields[join_field_1].beg;
  262.     }
  263.   else
  264.     {
  265.       beg1 = NULL;
  266.       len1 = 0;
  267.     }
  268.  
  269.   if (join_field_2 < line2->nfields)
  270.     {
  271.       beg2 = line2->fields[join_field_2].beg;
  272.       len2 = line2->fields[join_field_2].lim
  273.     - line2->fields[join_field_2].beg;
  274.     }
  275.   else
  276.     {
  277.       beg2 = NULL;
  278.       len2 = 0;
  279.     }
  280.  
  281.   if (len1 == 0)
  282.     return len2 == 0 ? 0 : -1;
  283.   if (len2 == 0)
  284.     return 1;
  285.   diff = memcmp (beg1, beg2, min (len1, len2));
  286.   if (diff)
  287.     return diff;
  288.   return len1 - len2;
  289. }
  290.  
  291. /* Print field N of LINE if it exists and is nonempty, otherwise
  292.    `empty_filler' if it is nonempty. */
  293.  
  294. static void
  295. prfield (n, line)
  296.      int n;
  297.      struct line *line;
  298. {
  299.   int len;
  300.  
  301.   if (n < line->nfields)
  302.     {
  303.       len = line->fields[n].lim - line->fields[n].beg;
  304.       if (len)
  305.     fwrite (line->fields[n].beg, 1, len, stdout);
  306.       else if (empty_filler)
  307.     fputs (empty_filler, stdout);
  308.     }
  309.   else if (empty_filler)
  310.     fputs (empty_filler, stdout);
  311. }
  312.  
  313. /* Print LINE, with its fields separated by `tab'. */
  314.  
  315. static void
  316. prline (line)
  317.      struct line *line;
  318. {
  319.   int i;
  320.  
  321.   for (i = 0; i < line->nfields; ++i)
  322.     {
  323.       prfield (i, line);
  324.       if (i == line->nfields - 1)
  325.     putchar ('\n');
  326.       else
  327.     putchar (tab ? tab : ' ');
  328.     }
  329. }
  330.  
  331. /* Print the join of LINE1 and LINE2. */
  332.  
  333. static void
  334. prjoin (line1, line2)
  335.      struct line *line1;
  336.      struct line *line2;
  337. {
  338.   if (outlist)
  339.     {
  340.       struct outlist *o;
  341.  
  342.       prfield (outlist->field - 1, outlist->file == 1 ? line1 : line2);
  343.       for (o = outlist->next; o; o = o->next)
  344.     {
  345.       putchar (tab ? tab : ' ');
  346.       prfield (o->field - 1, o->file == 1 ? line1 : line2);
  347.     }
  348.       putchar ('\n');
  349.     }
  350.   else
  351.     {
  352.       int i;
  353.  
  354.       prfield (join_field_1, line1);
  355.       for (i = 0; i < join_field_1 && i < line1->nfields; ++i)
  356.     {
  357.       putchar (tab ? tab : ' ');
  358.       prfield (i, line1);
  359.     }
  360.       for (i = join_field_1 + 1; i < line1->nfields; ++i)
  361.     {
  362.       putchar (tab ? tab : ' ');
  363.       prfield (i, line1);
  364.     }
  365.  
  366.       for (i = 0; i < join_field_2 && i < line2->nfields; ++i)
  367.     {
  368.       putchar (tab ? tab : ' ');
  369.       prfield (i, line2);
  370.     }
  371.       for (i = join_field_2 + 1; i < line2->nfields; ++i)
  372.     {
  373.       putchar (tab ? tab : ' ');
  374.       prfield (i, line2);
  375.     }
  376.       putchar ('\n');
  377.     }
  378. }
  379.  
  380. /* Print the join of the files in FP1 and FP2. */
  381.  
  382. static void
  383. join (fp1, fp2)
  384.      FILE *fp1;
  385.      FILE *fp2;
  386. {
  387.   struct seq seq1, seq2;
  388.   struct line line;
  389.   int diff, i, j, eof1, eof2;
  390.  
  391.   /* Read the first line of each file. */
  392.   initseq (&seq1);
  393.   getseq (fp1, &seq1);
  394.   initseq (&seq2);
  395.   getseq (fp2, &seq2);
  396.  
  397.   while (seq1.count && seq2.count)
  398.     {
  399.       diff = keycmp (&seq1.lines[0], &seq2.lines[0]);
  400.       if (diff < 0)
  401.     {
  402.       if (print_unpairables_1)
  403.         prline (&seq1.lines[0]);
  404.       freeline (&seq1.lines[0]);
  405.       seq1.count = 0;
  406.       getseq (fp1, &seq1);
  407.       continue;
  408.     }
  409.       if (diff > 0)
  410.     {
  411.       if (print_unpairables_2)
  412.         prline (&seq2.lines[0]);
  413.       freeline (&seq2.lines[0]);
  414.       seq2.count = 0;
  415.       getseq (fp2, &seq2);
  416.       continue;
  417.     }
  418.  
  419.       /* Keep reading lines from file1 as long as they continue to
  420.      match the current line from file2. */
  421.       eof1 = 0;
  422.       do
  423.     if (!getseq (fp1, &seq1))
  424.       {
  425.         eof1 = 1;
  426.         ++seq1.count;
  427.         break;
  428.       }
  429.       while (!keycmp (&seq1.lines[seq1.count - 1], &seq2.lines[0]));
  430.  
  431.       /* Keep reading lines from file2 as long as they continue to
  432.      match the current line from file1. */
  433.       eof2 = 0;
  434.       do
  435.     if (!getseq (fp2, &seq2))
  436.       {
  437.         eof2 = 1;
  438.         ++seq2.count;
  439.         break;
  440.       }
  441.       while (!keycmp (&seq1.lines[0], &seq2.lines[seq2.count - 1]));
  442.  
  443.       if (print_pairables)
  444.     {
  445.       for (i = 0; i < seq1.count - 1; ++i)
  446.         for (j = 0; j < seq2.count - 1; ++j)
  447.           prjoin (&seq1.lines[i], &seq2.lines[j]);
  448.     }
  449.  
  450.       for (i = 0; i < seq1.count - 1; ++i)
  451.     freeline (&seq1.lines[i]);
  452.       if (!eof1)
  453.     {
  454.       seq1.lines[0] = seq1.lines[seq1.count - 1];
  455.       seq1.count = 1;
  456.     }
  457.       else
  458.     seq1.count = 0;
  459.  
  460.       for (i = 0; i < seq2.count - 1; ++i)
  461.     freeline (&seq2.lines[i]);
  462.       if (!eof2)
  463.     {
  464.       seq2.lines[0] = seq2.lines[seq2.count - 1];
  465.       seq2.count = 1;
  466.     }
  467.       else
  468.     seq2.count = 0;
  469.     }
  470.  
  471.   if (print_unpairables_1 && seq1.count)
  472.     {
  473.       prline (&seq1.lines[0]);
  474.       freeline (&seq1.lines[0]);
  475.       while (get_line (fp1, &line))
  476.     {
  477.       prline (&line);
  478.       freeline (&line);
  479.     }
  480.     }
  481.  
  482.   if (print_unpairables_2 && seq2.count)
  483.     {
  484.       prline (&seq2.lines[0]);
  485.       freeline (&seq2.lines[0]);
  486.       while (get_line (fp2, &line))
  487.     {
  488.       prline (&line);
  489.       freeline (&line);
  490.     }
  491.     }
  492.  
  493.   delseq (&seq1);
  494.   delseq (&seq2);
  495. }
  496.  
  497. /* Add a field spec for field FIELD of file FILE to `outlist' and return 1,
  498.    unless either argument is invalid; then just return 0. */
  499.  
  500. static int
  501. add_field (file, field)
  502.      int file;
  503.      int field;
  504. {
  505.   struct outlist *o;
  506.  
  507.   if (file < 1 || file > 2 || field < 1)
  508.     return 0;
  509.   o = (struct outlist *) xmalloc (sizeof (struct outlist));
  510.   o->file = file;
  511.   o->field = field;
  512.   o->next = NULL;
  513.  
  514.   /* Add to the end of the list so the fields are in the right order. */
  515.   if (outlist == NULL)
  516.     outlist = o;
  517.   else
  518.     outlist_end->next = o;
  519.   outlist_end = o;
  520.  
  521.   return 1;
  522. }
  523.  
  524. /* Add the comma or blank separated field spec(s) in STR to `outlist'.
  525.    Return the number of fields added. */
  526.  
  527. static int
  528. add_field_list (str)
  529.      char *str;
  530. {
  531.   int added = 0;
  532.   int file = -1, field = -1;
  533.   int dot_found = 0;
  534.  
  535.   for (; *str; str++)
  536.     {
  537.       if (*str == ',' || ISBLANK (*str))
  538.     {
  539.       added += add_field (file, field);
  540.       file = field = -1;
  541.       dot_found = 0;
  542.     }
  543.       else if (*str == '.')
  544.     dot_found = 1;
  545.       else if (ISDIGIT (*str))
  546.     {
  547.       if (!dot_found)
  548.         {
  549.           if (file == -1)
  550.         file = 0;
  551.           file = file * 10 + *str - '0';
  552.         }
  553.       else
  554.         {
  555.           if (field == -1)
  556.         field = 0;
  557.           field = field * 10 + *str - '0';
  558.         }
  559.     }
  560.       else
  561.     return 0;
  562.     }
  563.  
  564.   added += add_field (file, field);
  565.   return added;
  566. }
  567.  
  568. void
  569. main (argc, argv)
  570.      int argc;
  571.      char *argv[];
  572. {
  573.   char *names[2];
  574.   FILE *fp1, *fp2;
  575.   int optc, prev_optc = 0, nfiles, val;
  576.  
  577.   program_name = argv[0];
  578.   nfiles = 0;
  579.   print_pairables = 1;
  580.  
  581.   while ((optc = getopt_long_only (argc, argv, "-a:e:1:2:o:t:v:", longopts,
  582.                    (int *) 0)) != EOF)
  583.     {
  584.       switch (optc)
  585.     {
  586.     case 0:
  587.       break;
  588.  
  589.     case 'a':
  590.       val = atoi (optarg);
  591.       if (val == 1)
  592.         print_unpairables_1 = 1;
  593.       else if (val == 2)
  594.         print_unpairables_2 = 1;
  595.       else
  596.         error (2, 0, "invalid file number for `-a'");
  597.       break;
  598.  
  599.     case 'e':
  600.       empty_filler = optarg;
  601.       break;
  602.  
  603.     case '1':
  604.       val = atoi (optarg);
  605.       if (val <= 0)
  606.         error (2, 0, "invalid field number for `-1'");
  607.       join_field_1 = val - 1;
  608.       break;
  609.  
  610.     case '2':
  611.       val = atoi (optarg);
  612.       if (val <= 0)
  613.         error (2, 0, "invalid field number for `-2'");
  614.       join_field_2 = val - 1;
  615.       break;
  616.  
  617.     case 'j':
  618.       val = atoi (optarg);
  619.       if (val <= 0)
  620.         error (2, 0, "invalid field number for `-j'");
  621.       join_field_1 = join_field_2 = val - 1;
  622.       break;
  623.  
  624.     case 'o':
  625.       if (add_field_list (optarg) == 0)
  626.         error (2, 0, "invalid field list for `-o'");
  627.       break;
  628.  
  629.     case 't':
  630.       tab = *optarg;
  631.       break;
  632.  
  633.     case 'v':
  634.       val = atoi (optarg);
  635.       if (val == 1)
  636.         print_unpairables_1 = 1;
  637.       else if (val == 2)
  638.         print_unpairables_2 = 1;
  639.       else
  640.         error (2, 0, "invalid file number for `-v'");
  641.       print_pairables = 0;
  642.       break;
  643.  
  644.     case 1:            /* Non-option argument. */
  645.       if (prev_optc == 'o')
  646.         {
  647.           /* Might be continuation of args to -o. */
  648.           if (add_field_list (optarg) > 0)
  649.         continue;    /* Don't change `prev_optc'. */
  650.         }
  651.  
  652.       if (nfiles > 1)
  653.         usage ();
  654.       names[nfiles++] = optarg;
  655.       break;
  656.  
  657.     case '?':
  658.       usage ();
  659.     }
  660.       prev_optc = optc;
  661.     }
  662.  
  663.   if (flag_version)
  664.     {
  665.       fprintf (stderr, "%s\n", version_string);
  666.       exit (0);
  667.     }
  668.  
  669.   if (flag_help)
  670.     usage ();
  671.   
  672.   if (nfiles != 2)
  673.     usage ();
  674.  
  675.   fp1 = strcmp (names[0], "-") ? fopen (names[0], "r") : stdin;
  676.   if (!fp1)
  677.     error (1, errno, "%s", names[0]);
  678.   fp2 = strcmp (names[1], "-") ? fopen (names[1], "r") : stdin;
  679.   if (!fp2)
  680.     error (1, errno, "%s", names[1]);
  681.   if (fp1 == fp2)
  682.     error (1, errno, "both files cannot be standard input");
  683.   join (fp1, fp2);
  684.  
  685.   if ((fp1 == stdin || fp2 == stdin) && fclose (stdin) == EOF)
  686.     error (1, errno, "-");
  687.   if (ferror (stdout) || fclose (stdout) == EOF)
  688.     error (1, errno, "write error");
  689.  
  690.   exit (0);
  691. }
  692.  
  693. static void
  694. usage ()
  695. {
  696.   fprintf (stderr, "\
  697. Usage: %s [-a 1|2] [-v 1|2] [-e empty-string] [-o field-list...] [-t char]\n\
  698.        [-j[1|2] field] [-1 field] [-2 field] file1 file2\n",
  699.        program_name);
  700.   exit (1);
  701. }
  702.