home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / paste.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  12.5 KB  |  502 lines

  1. /* paste - merge lines of files
  2.    Copyright (C) 1984 by David M. Ihnat
  3.  
  4.    This program is a total rewrite of the Bell Laboratories Unix(Tm)
  5.    command of the same name, as of System V.  It contains no proprietary
  6.    code, and therefore may be used without violation of any proprietary
  7.    agreements whatsoever.  However, you will notice that the program is
  8.    copyrighted by me.  This is to assure the program does *not* fall
  9.    into the public domain.  Thus, I may specify just what I am now:
  10.    This program may be freely copied and distributed, provided this notice
  11.    remains; it may not be sold for profit without express written consent of
  12.    the author.
  13.    Please note that I recreated the behavior of the Unix(Tm) 'paste' command
  14.    as faithfully as possible, with minor exceptions; however,
  15.    I haven't run a full set of regression tests.  Thus, the user of
  16.    this program accepts full responsibility for any effects or loss;
  17.    in particular, the author is not responsible for any losses,
  18.    explicit or incidental, that may be incurred through use of this program.
  19.  
  20.    I ask that any bugs (and, if possible, fixes) be reported to me when
  21.    possible.  -David Ihnat (312) 784-4544 ignatz@homebru.chi.il.us
  22.  
  23.    The list of valid escape sequences has been expanded over the Unix
  24.    version, to include \b, \f, \r, and \v.
  25.  
  26.    POSIX changes, bug fixes, long-named options, and cleanup
  27.    by David MacKenzie <djm@gnu.ai.mit.edu>.
  28.  
  29.    Options:
  30.    --serial
  31.    -s                Paste one file at a time rather than
  32.                 one line from each file.
  33.    --delimiters=delim-list
  34.    -d delim-list        Consecutively use the characters in
  35.                 DELIM-LIST instead of tab to separate
  36.                 merged lines.  When DELIM-LIST is exhausted,
  37.                 start again at its beginning.
  38.    A FILE of `-' means standard input.
  39.    If no FILEs are given, standard input is used. */
  40.  
  41. #include <config.h>
  42.  
  43. #include <stdio.h>
  44. #include <getopt.h>
  45. #include <sys/types.h>
  46. #include "system.h"
  47. #include "version.h"
  48.  
  49. void error ();
  50. char *xmalloc ();
  51. char *xrealloc ();
  52.  
  53. static char *collapse_escapes ();
  54. static int paste_parallel ();
  55. static int paste_serial ();
  56. static void usage ();
  57.  
  58. /* Indicates that no delimiter should be added in the current position. */
  59. #define EMPTY_DELIM '\0'
  60.  
  61. /* Element marking a file that has reached EOF and been closed. */
  62. #define    CLOSED ((FILE *) -1)
  63.  
  64. /* Element marking end of list of open files. */
  65. #define ENDLIST ((FILE *) -2)
  66.  
  67. /* Name this program was run with. */
  68. char *program_name;
  69.  
  70. /* If nonzero, we have read standard input at some point. */
  71. static int have_read_stdin;
  72.  
  73. /* If nonzero, merge subsequent lines of each file rather than
  74.    corresponding lines from each file in parallel. */
  75. static int serial_merge;
  76.  
  77. /* The delimeters between lines of input files (used cyclically). */
  78. static char *delims;
  79.  
  80. /* A pointer to the character after the end of `delims'. */
  81. static char *delim_end;
  82.  
  83. /* If non-zero, display usage information and exit.  */
  84. static int show_help;
  85.  
  86. /* If non-zero, print the version on standard output then exit.  */
  87. static int show_version;
  88.  
  89. static struct option const longopts[] =
  90. {
  91.   {"serial", no_argument, 0, 's'},
  92.   {"delimiters", required_argument, 0, 'd'},
  93.   {"help", no_argument, &show_help, 1},
  94.   {"version", no_argument, &show_version, 1},
  95.   {0, 0, 0, 0}
  96. };
  97.  
  98. main (argc, argv)
  99.      int argc;
  100.      char **argv;
  101. {
  102.   int optc, exit_status;
  103.   char default_delims[2], zero_delims[3];
  104.  
  105.   program_name = argv[0];
  106.   have_read_stdin = 0;
  107.   serial_merge = 0;
  108.   delims = default_delims;
  109.   strcpy (delims, "\t");
  110.   strcpy (zero_delims, "\\0");
  111.  
  112.   while ((optc = getopt_long (argc, argv, "d:s", longopts, (int *) 0))
  113.      != EOF)
  114.     {
  115.       switch (optc)
  116.     {
  117.     case 0:
  118.       break;
  119.  
  120.     case 'd':
  121.       /* Delimiter character(s). */
  122.       if (optarg[0] == '\0')
  123.         optarg = zero_delims;
  124.       delims = optarg;
  125.       break;
  126.  
  127.     case 's':
  128.       serial_merge++;
  129.       break;
  130.  
  131.     default:
  132.       usage (1);
  133.     }
  134.     }
  135.  
  136.   if (show_version)
  137.     {
  138.       printf ("paste - %s\n", version_string);
  139.       exit (0);
  140.     }
  141.  
  142.   if (show_help)
  143.     usage (0);
  144.  
  145.   if (optind == argc)
  146.     argv[argc++] = "-";
  147.  
  148.   delim_end = collapse_escapes (delims);
  149.  
  150.   if (!serial_merge)
  151.     exit_status = paste_parallel (argc - optind, &argv[optind]);
  152.   else
  153.     exit_status = paste_serial (argc - optind, &argv[optind]);
  154.   if (have_read_stdin && fclose (stdin) == EOF)
  155.     error (1, errno, "-");
  156.   if (ferror (stdout) || fclose (stdout) == EOF)
  157.     error (1, errno, "write error");
  158.   exit (exit_status);
  159. }
  160.  
  161. /* Replace backslash representations of special characters in
  162.    STRPTR with their actual values.
  163.    The set of possible backslash characters has been expanded beyond
  164.    that recognized by the Unix version.
  165.  
  166.    Return a pointer to the character after the new end of STRPTR. */
  167.  
  168. static char *
  169. collapse_escapes (strptr)
  170.      char *strptr;
  171. {
  172.   register char *strout;
  173.  
  174.   strout = strptr;        /* Start at the same place, anyway. */
  175.  
  176.   while (*strptr)
  177.     {
  178.       if (*strptr != '\\')    /* Is it an escape character? */
  179.     *strout++ = *strptr++;    /* No, just transfer it. */
  180.       else
  181.     {
  182.       switch (*++strptr)
  183.         {
  184.         case '0':
  185.           *strout++ = EMPTY_DELIM;
  186.           break;
  187.  
  188.         case 'b':
  189.           *strout++ = '\b';
  190.           break;
  191.  
  192.         case 'f':
  193.           *strout++ = '\f';
  194.           break;
  195.  
  196.         case 'n':
  197.           *strout++ = '\n';
  198.           break;
  199.  
  200.         case 'r':
  201.           *strout++ = '\r';
  202.           break;
  203.  
  204.         case 't':
  205.           *strout++ = '\t';
  206.           break;
  207.  
  208.         case 'v':
  209.           *strout++ = '\v';
  210.           break;
  211.  
  212.         default:
  213.           *strout++ = *strptr;
  214.           break;
  215.         }
  216.       strptr++;
  217.     }
  218.     }
  219.   return strout;
  220. }
  221.  
  222. /* Perform column paste on the NFILES files named in FNAMPTR.
  223.    Return 0 if no errors, 1 if one or more files could not be
  224.    opened or read. */
  225.  
  226. static int
  227. paste_parallel (nfiles, fnamptr)
  228.      int nfiles;
  229.      char **fnamptr;
  230. {
  231.   int errors = 0;        /* 1 if open or read errors occur. */
  232.   /* Number of files for which space is allocated in `delbuf' and `fileptr'.
  233.      Enlarged as necessary. */
  234.   int file_list_size = 12;
  235.   int chr;            /* Input character. */
  236.   int line_length;        /* Number of chars in line. */
  237.   int somedone;            /* 0 if all files empty for this line. */
  238.   /* If all files are just ready to be closed, or will be on this
  239.      round, the string of delimiters must be preserved.
  240.      delbuf[0] through delbuf[file_list_size]
  241.      store the delimiters for closed files. */
  242.   char *delbuf;
  243.   int delims_saved;        /* Number of delims saved in `delbuf'. */
  244.   register char *delimptr;    /* Cycling pointer into `delims'. */
  245.   FILE **fileptr;        /* Streams open to the files to process. */
  246.   int files_open;        /* Number of files still open to process. */
  247.   int i;            /* Loop index. */
  248.   int opened_stdin = 0;        /* Nonzero if any fopen got fd 0. */
  249.  
  250. #ifdef lint  /* Suppress `used before initialized' warning.  */
  251.   chr = 0;
  252. #endif
  253.  
  254.   delbuf = (char *) xmalloc (file_list_size + 2);
  255.   fileptr = (FILE **) xmalloc ((file_list_size + 1) * sizeof (FILE *));
  256.  
  257.   /* Attempt to open all files.  This could be expanded to an infinite
  258.      number of files, but at the (considerable) expense of remembering
  259.      each file and its current offset, then opening/reading/closing.  */
  260.  
  261.   for (files_open = 0; files_open < nfiles; ++files_open)
  262.     {
  263.       if (files_open == file_list_size - 2)
  264.     {
  265.       file_list_size += 12;
  266.       delbuf = (char *) xrealloc (delbuf, file_list_size + 2);
  267.       fileptr = (FILE **) xrealloc (fileptr, (file_list_size + 1)
  268.                     * sizeof (FILE *));
  269.     }
  270.       if (!strcmp (fnamptr[files_open], "-"))
  271.     {
  272.       have_read_stdin = 1;
  273.       fileptr[files_open] = stdin;
  274.     }
  275.       else
  276.     {
  277.       fileptr[files_open] = fopen (fnamptr[files_open], "r");
  278.       if (fileptr[files_open] == NULL)
  279.         error (1, errno, "%s", fnamptr[files_open]);
  280.       else if (fileno (fileptr[files_open]) == 0)
  281.         opened_stdin = 1;
  282.     }
  283.     }
  284.  
  285.   fileptr[files_open] = ENDLIST;
  286.  
  287.   if (opened_stdin && have_read_stdin)
  288.     error (1, 0, "standard input is closed");
  289.  
  290.   /* Read a line from each file and output it to stdout separated by a
  291.      delimiter, until we go through the loop without successfully
  292.      reading from any of the files. */
  293.  
  294.   while (files_open)
  295.     {
  296.       /* Set up for the next line. */
  297.       somedone = 0;
  298.       delimptr = delims;
  299.       delims_saved = 0;
  300.  
  301.       for (i = 0; fileptr[i] != ENDLIST && files_open; i++)
  302.     {
  303.       line_length = 0;    /* Clear so we can easily detect EOF. */
  304.       if (fileptr[i] != CLOSED)
  305.         {
  306.           chr = getc (fileptr[i]);
  307.           if (chr != EOF && delims_saved)
  308.         {
  309.           fwrite (delbuf, sizeof (char), delims_saved, stdout);
  310.           delims_saved = 0;
  311.         }
  312.  
  313.           while (chr != EOF)
  314.         {
  315.           line_length++;
  316.           if (chr == '\n')
  317.             break;
  318.           putc (chr, stdout);
  319.           chr = getc (fileptr[i]);
  320.         }
  321.         }
  322.  
  323.       if (line_length == 0)
  324.         {
  325.           /* EOF, read error, or closed file.
  326.          If an EOF or error, close the file and mark it in the list. */
  327.           if (fileptr[i] != CLOSED)
  328.         {
  329.           if (ferror (fileptr[i]))
  330.             {
  331.               error (0, errno, "%s", fnamptr[i]);
  332.               errors = 1;
  333.             }
  334.           if (fileptr[i] == stdin)
  335.             clearerr (fileptr[i]); /* Also clear EOF. */
  336.           else if (fclose (fileptr[i]) == EOF)
  337.             {
  338.               error (0, errno, "%s", fnamptr[i]);
  339.               errors = 1;
  340.             }
  341.  
  342.           fileptr[i] = CLOSED;
  343.           files_open--;
  344.         }
  345.  
  346.           if (fileptr[i + 1] == ENDLIST)
  347.         {
  348.           /* End of this output line.
  349.              Is this the end of the whole thing? */
  350.           if (somedone)
  351.             {
  352.               /* No.  Some files were not closed for this line. */
  353.               if (delims_saved)
  354.             {
  355.               fwrite (delbuf, sizeof (char), delims_saved, stdout);
  356.               delims_saved = 0;
  357.             }
  358.               putc ('\n', stdout);
  359.             }
  360.           continue;    /* Next read of files, or exit. */
  361.         }
  362.           else
  363.         {
  364.           /* Closed file; add delimiter to `delbuf'. */
  365.           if (*delimptr != EMPTY_DELIM)
  366.             delbuf[delims_saved++] = *delimptr;
  367.           if (++delimptr == delim_end)
  368.             delimptr = delims;
  369.         }
  370.         }
  371.       else
  372.         {
  373.           /* Some data read. */
  374.           somedone++;
  375.  
  376.           /* Except for last file, replace last newline with delim. */
  377.           if (fileptr[i + 1] != ENDLIST)
  378.         {
  379.           if (chr != '\n')
  380.             putc (chr, stdout);
  381.           if (*delimptr != EMPTY_DELIM)
  382.             putc (*delimptr, stdout);
  383.           if (++delimptr == delim_end)
  384.             delimptr = delims;
  385.         }
  386.           else
  387.         putc (chr, stdout);
  388.         }
  389.     }
  390.     }
  391.   return errors;
  392. }
  393.  
  394. /* Perform serial paste on the NFILES files named in FNAMPTR.
  395.    Return 0 if no errors, 1 if one or more files could not be
  396.    opened or read. */
  397.  
  398. static int
  399. paste_serial (nfiles, fnamptr)
  400.      int nfiles;
  401.      char **fnamptr;
  402. {
  403.   int errors = 0;        /* 1 if open or read errors occur. */
  404.   register int charnew, charold; /* Current and previous char read. */
  405.   register char *delimptr;    /* Current delimiter char. */
  406.   register FILE *fileptr;    /* Open for reading current file. */
  407.  
  408.   for (; nfiles; nfiles--, fnamptr++)
  409.     {
  410.       if (!strcmp (*fnamptr, "-"))
  411.     {
  412.       have_read_stdin = 1;
  413.       fileptr = stdin;
  414.     }
  415.       else
  416.     {
  417.       fileptr = fopen (*fnamptr, "r");
  418.       if (fileptr == NULL)
  419.         {
  420.           error (0, errno, "%s", *fnamptr);
  421.           errors = 1;
  422.           continue;
  423.         }
  424.     }
  425.  
  426.       delimptr = delims;    /* Set up for delimiter string. */
  427.  
  428.       charold = getc (fileptr);
  429.       if (charold != EOF)
  430.     {
  431.       /* `charold' is set up.  Hit it!
  432.          Keep reading characters, stashing them in `charnew';
  433.          output `charold', converting to the appropriate delimiter
  434.          character if needed.  After the EOF, output `charold'
  435.          if it's a newline; otherwise, output it and then a newline. */
  436.  
  437.       while ((charnew = getc (fileptr)) != EOF)
  438.         {
  439.           /* Process the old character. */
  440.           if (charold == '\n')
  441.         {
  442.           if (*delimptr != EMPTY_DELIM)
  443.             putc (*delimptr, stdout);
  444.  
  445.           if (++delimptr == delim_end)
  446.             delimptr = delims;
  447.         }
  448.           else
  449.         putc (charold, stdout);
  450.  
  451.           charold = charnew;
  452.         }
  453.  
  454.       /* Hit EOF.  Process that last character. */
  455.       putc (charold, stdout);
  456.     }
  457.  
  458.       if (charold != '\n')
  459.     putc ('\n', stdout);
  460.  
  461.       if (ferror (fileptr))
  462.     {
  463.       error (0, errno, "%s", *fnamptr);
  464.       errors = 1;
  465.     }
  466.       if (fileptr == stdin)
  467.     clearerr (fileptr);    /* Also clear EOF. */
  468.       else if (fclose (fileptr) == EOF)
  469.     {
  470.       error (0, errno, "%s", *fnamptr);
  471.       errors = 1;
  472.     }
  473.     }
  474.   return errors;
  475. }
  476.  
  477. static void
  478. usage (status)
  479.      int status;
  480. {
  481.   if (status != 0)
  482.     fprintf (stderr, "Try `%s --help' for more information.\n",
  483.          program_name);
  484.   else
  485.     {
  486.       printf ("\
  487. Usage: %s [OPTION]... [FILE]...\n\
  488. ",
  489.           program_name);
  490.       printf ("\
  491. \n\
  492.   -d, --delimiters=LIST   reuse characters from LIST instead of TABs\n\
  493.   -s, --serial            paste one file at a time instead of in parallel\n\
  494.       --help              display this help and exit\n\
  495.       --version           output version information and exit\n\
  496. \n\
  497. With no INPUT, or when INPUT is -, read standard input.\n\
  498. ");
  499.     }
  500.   exit (status);
  501. }
  502.