home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / txtut122.zip / textutil / src / fold.c < prev    next >
C/C++ Source or Header  |  1998-04-11  |  8KB  |  339 lines

  1. /* fold -- wrap each input line to fit in specified width.
  2.    Copyright (C) 91, 95, 1996 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 Foundation,
  16.    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  17.  
  18. /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
  19.  
  20. #include <config.h>
  21.  
  22. /* Get isblank from GNU libc.  */
  23. #define _GNU_SOURCE
  24.  
  25. #include <stdio.h>
  26. #include <getopt.h>
  27. #include <sys/types.h>
  28.  
  29. #if HAVE_LIMITS_H
  30. # include <limits.h>
  31. #endif
  32.  
  33. #ifndef UINT_MAX
  34. # define UINT_MAX ((unsigned int) ~(unsigned int) 0)
  35. #endif
  36.  
  37. #ifndef INT_MAX
  38. # define INT_MAX ((int) (UINT_MAX >> 1))
  39. #endif
  40.  
  41. #include "system.h"
  42. #include "xstrtol.h"
  43. #include "error.h"
  44.  
  45. char *xrealloc ();
  46. char *xmalloc ();
  47.  
  48. /* The name this program was run with. */
  49. char *program_name;
  50.  
  51. /* If nonzero, try to break on whitespace. */
  52. static int break_spaces;
  53.  
  54. /* If nonzero, count bytes, not column positions. */
  55. static int count_bytes;
  56.  
  57. /* If nonzero, at least one of the files we read was standard input. */
  58. static int have_read_stdin;
  59.  
  60. /* If nonzero, display usage information and exit.  */
  61. static int show_help;
  62.  
  63. /* If nonzero, print the version on standard output then exit.  */
  64. static int show_version;
  65.  
  66. static struct option const longopts[] =
  67. {
  68.   {"bytes", no_argument, NULL, 'b'},
  69.   {"spaces", no_argument, NULL, 's'},
  70.   {"width", required_argument, NULL, 'w'},
  71.   {"help", no_argument, &show_help, 1},
  72.   {"version", no_argument, &show_version, 1},
  73.   {NULL, 0, NULL, 0}
  74. };
  75.  
  76. static void
  77. usage (int status)
  78. {
  79.   if (status != 0)
  80.     fprintf (stderr, _("Try `%s --help' for more information.\n"),
  81.          program_name);
  82.   else
  83.     {
  84.       printf (_("\
  85. Usage: %s [OPTION]... [FILE]...\n\
  86. "),
  87.           program_name);
  88.       printf (_("\
  89. Wrap input lines in each FILE (standard input by default), writing to\n\
  90. standard output.\n\
  91. \n\
  92.   -b, --bytes         count bytes rather than columns\n\
  93.   -s, --spaces        break at spaces\n\
  94.   -w, --width=WIDTH   use WIDTH columns instead of 80\n\
  95. "));
  96.       puts (_("\nReport bugs to textutils-bugs@gnu.ai.mit.edu"));
  97.     }
  98.   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
  99. }
  100.  
  101. /* Assuming the current column is COLUMN, return the column that
  102.    printing C will move the cursor to.
  103.    The first column is 0. */
  104.  
  105. static int
  106. adjust_column (int column, char c)
  107. {
  108.   if (!count_bytes)
  109.     {
  110.       if (c == '\b')
  111.     {
  112.       if (column > 0)
  113.         column--;
  114.     }
  115.       else if (c == '\r')
  116.     column = 0;
  117.       else if (c == '\t')
  118.     column = column + 8 - column % 8;
  119.       else /* if (isprint (c)) */
  120.     column++;
  121.     }
  122.   else
  123.     column++;
  124.   return column;
  125. }
  126.  
  127. /* Fold file FILENAME, or standard input if FILENAME is "-",
  128.    to stdout, with maximum line length WIDTH.
  129.    Return 0 if successful, 1 if an error occurs. */
  130.  
  131. static int
  132. fold_file (char *filename, int width)
  133. {
  134.   FILE *istream;
  135.   register int c;
  136.   int column = 0;        /* Screen column where next char will go. */
  137.   int offset_out = 0;    /* Index in `line_out' for next char. */
  138.   static char *line_out = NULL;
  139.   static int allocated_out = 0;
  140.  
  141.   if (!strcmp (filename, "-"))
  142.     {
  143.       istream = stdin;
  144.       have_read_stdin = 1;
  145.     }
  146.   else
  147.     istream = fopen (filename, "r");
  148.  
  149.   if (istream == NULL)
  150.     {
  151.       error (0, errno, "%s", filename);
  152.       return 1;
  153.     }
  154.  
  155.   while ((c = getc (istream)) != EOF)
  156.     {
  157.       if (offset_out + 1 >= allocated_out)
  158.     {
  159.       allocated_out += 1024;
  160.       line_out = xrealloc (line_out, allocated_out);
  161.     }
  162.  
  163.       if (c == '\n')
  164.     {
  165.       line_out[offset_out++] = c;
  166.       fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
  167.       column = offset_out = 0;
  168.       continue;
  169.     }
  170.  
  171.     rescan:
  172.       column = adjust_column (column, c);
  173.  
  174.       if (column > width)
  175.     {
  176.       /* This character would make the line too long.
  177.          Print the line plus a newline, and make this character
  178.          start the next line. */
  179.       if (break_spaces)
  180.         {
  181.           /* Look for the last blank. */
  182.           int logical_end;
  183.  
  184.           for (logical_end = offset_out - 1; logical_end >= 0;
  185.            logical_end--)
  186.         if (ISBLANK (line_out[logical_end]))
  187.           break;
  188.           if (logical_end >= 0)
  189.         {
  190.           int i;
  191.  
  192.           /* Found a blank.  Don't output the part after it. */
  193.           logical_end++;
  194.           fwrite (line_out, sizeof (char), (size_t) logical_end,
  195.               stdout);
  196.           putchar ('\n');
  197.           /* Move the remainder to the beginning of the next line.
  198.              The areas being copied here might overlap. */
  199.           memmove (line_out, line_out + logical_end,
  200.                offset_out - logical_end);
  201.           offset_out -= logical_end;
  202.           for (column = i = 0; i < offset_out; i++)
  203.             column = adjust_column (column, line_out[i]);
  204.           goto rescan;
  205.         }
  206.         }
  207.       else
  208.         {
  209.           if (offset_out == 0)
  210.         {
  211.           line_out[offset_out++] = c;
  212.           continue;
  213.         }
  214.         }
  215.       line_out[offset_out++] = '\n';
  216.       fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
  217.       column = offset_out = 0;
  218.       goto rescan;
  219.     }
  220.  
  221.       line_out[offset_out++] = c;
  222.     }
  223.  
  224.   if (offset_out)
  225.     fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
  226.  
  227.   if (ferror (istream))
  228.     {
  229.       error (0, errno, "%s", filename);
  230.       if (strcmp (filename, "-"))
  231.     fclose (istream);
  232.       return 1;
  233.     }
  234.   if (strcmp (filename, "-") && fclose (istream) == EOF)
  235.     {
  236.       error (0, errno, "%s", filename);
  237.       return 1;
  238.     }
  239.  
  240.   if (ferror (stdout))
  241.     {
  242.       error (0, errno, _("write error"));
  243.       return 1;
  244.     }
  245.  
  246.   return 0;
  247. }
  248.  
  249. int
  250. main (int argc, char **argv)
  251. {
  252.   int width = 80;
  253.   int i;
  254.   int optc;
  255.   int errs = 0;
  256.  
  257. #ifdef __EMX__
  258. _wildcard(&argc, &argv);
  259. #endif
  260.  
  261.  
  262.   program_name = argv[0];
  263. #ifndef __EMX__
  264.   setlocale (LC_ALL, "");
  265.   bindtextdomain (PACKAGE, LOCALEDIR);
  266.   textdomain (PACKAGE);
  267. #endif
  268.   break_spaces = count_bytes = have_read_stdin = 0;
  269.  
  270.   /* Turn any numeric options into -w options.  */
  271.   for (i = 1; i < argc; i++)
  272.     {
  273.       if (argv[i][0] == '-' && ISDIGIT (argv[i][1]))
  274.     {
  275.       char *s;
  276.  
  277.       s = xmalloc (strlen (argv[i]) + 2);
  278.       s[0] = '-';
  279.       s[1] = 'w';
  280.       strcpy (s + 2, argv[i] + 1);
  281.       argv[i] = s;
  282.     }
  283.     }
  284.  
  285.   while ((optc = getopt_long (argc, argv, "bsw:", longopts, (int *) 0))
  286.      != EOF)
  287.     {
  288.       switch (optc)
  289.     {
  290.     case 0:
  291.       break;
  292.  
  293.     case 'b':        /* Count bytes rather than columns. */
  294.       count_bytes = 1;
  295.       break;
  296.  
  297.     case 's':        /* Break at word boundaries. */
  298.       break_spaces = 1;
  299.       break;
  300.  
  301.     case 'w':        /* Line width. */
  302.       {
  303.         long int tmp_long;
  304.         if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
  305.         || tmp_long <= 0 || tmp_long > INT_MAX)
  306.           error (EXIT_FAILURE, 0,
  307.              _("invalid number of columns: `%s'"), optarg);
  308.         width = (int) tmp_long;
  309.       }
  310.       break;
  311.  
  312.     default:
  313.       usage (1);
  314.     }
  315.     }
  316.  
  317.   if (show_version)
  318.     {
  319.       printf ("fold (%s) %s\n", GNU_PACKAGE, VERSION);
  320.       exit (EXIT_SUCCESS);
  321.     }
  322.  
  323.   if (show_help)
  324.     usage (0);
  325.  
  326.   if (argc == optind)
  327.     errs |= fold_file ("-", width);
  328.   else
  329.     for (i = optind; i < argc; i++)
  330.       errs |= fold_file (argv[i], width);
  331.  
  332.   if (have_read_stdin && fclose (stdin) == EOF)
  333.     error (EXIT_FAILURE, errno, "-");
  334.   if (fclose (stdout) == EOF)
  335.     error (EXIT_FAILURE, errno, _("write error"));
  336.  
  337.   exit (errs == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
  338. }
  339.