Home | History | Annotate | Line # | Download | only in fold
fold.c revision 1.11
      1 /*	$NetBSD: fold.c,v 1.11 2000/09/08 12:57:28 mjl Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kevin Ruddy.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 __COPYRIGHT("@(#) Copyright (c) 1990, 1993\n\
     42 	The Regents of the University of California.  All rights reserved.\n");
     43 #endif /* not lint */
     44 
     45 #ifndef lint
     46 #if 0
     47 static char sccsid[] = "@(#)fold.c	8.1 (Berkeley) 6/6/93";
     48 #endif
     49 __RCSID("$NetBSD: fold.c,v 1.11 2000/09/08 12:57:28 mjl Exp $");
     50 #endif /* not lint */
     51 
     52 #include <stdio.h>
     53 #include <stdlib.h>
     54 #include <string.h>
     55 #include <unistd.h>
     56 #include <err.h>
     57 
     58 #define	DEFLINEWIDTH	80
     59 
     60 	int	main(int, char **);
     61 static	void	fold(int);
     62 static	int	new_column_position(int, int);
     63 static	void	usage(void);
     64 
     65 int count_bytes = 0;
     66 int split_words = 0;
     67 
     68 int
     69 main(int argc, char **argv)
     70 {
     71 	int ch;
     72 	int width;
     73 	char *p;
     74 
     75 	width = -1;
     76 	while ((ch = getopt(argc, argv, "0123456789bsw:")) != -1)
     77 		switch (ch) {
     78 		case 'b':
     79 			count_bytes = 1;
     80 			break;
     81 		case 's':
     82 			split_words = 1;
     83 			break;
     84 		case 'w':
     85 			if ((width = atoi(optarg)) <= 0)
     86 				errx(1, "illegal width value");
     87 			break;
     88 		case '0': case '1': case '2': case '3': case '4':
     89 		case '5': case '6': case '7': case '8': case '9':
     90 			if (width == -1) {
     91 				p = argv[optind - 1];
     92 				if (p[0] == '-' && p[1] == ch && !p[2])
     93 					width = atoi(++p);
     94 				else
     95 					width = atoi(argv[optind] + 1);
     96 			}
     97 			break;
     98 		default:
     99 			usage();
    100 		}
    101 	argv += optind;
    102 	argc -= optind;
    103 
    104 	if (width == -1)
    105 		width = DEFLINEWIDTH;
    106 
    107 	if (!*argv)
    108 		fold(width);
    109 	else for (; *argv; ++argv)
    110 		if (!freopen(*argv, "r", stdin)) {
    111 			err (1, "%s", *argv);
    112 			/* NOTREACHED */
    113 		} else
    114 			fold(width);
    115 	exit(0);
    116 }
    117 
    118 /*
    119  * Fold the contents of standard input to fit within WIDTH columns
    120  * (or bytes) and write to standard output.
    121  *
    122  * If split_words is set, split the line at the last space character
    123  * on the line.  This flag necessitates storing the line in a buffer
    124  * until the current column > width, or a newline or EOF is read.
    125  *
    126  * The buffer can grow larger than WIDTH due to backspaces and carriage
    127  * returns embedded in the input stream.
    128  */
    129 static void
    130 fold(int width)
    131 {
    132 	static char *buf = NULL;
    133 	static int   buf_max = 0;
    134 	int ch, col;
    135 	int indx;
    136 
    137 	col = indx = 0;
    138 	while ((ch = getchar()) != EOF) {
    139 		if (ch == '\n') {
    140 			if (indx != 0)
    141 				fwrite (buf, 1, indx, stdout);
    142 			putchar('\n');
    143 			col = indx = 0;
    144 			continue;
    145 		}
    146 
    147 		col = new_column_position (col, ch);
    148 		if (col > width) {
    149 			int i, last_space;
    150 
    151 #ifdef __GNUC__
    152 			last_space = 0;	/* XXX gcc */
    153 #endif
    154 			if (split_words) {
    155 				for (i = 0, last_space = -1; i < indx; i++)
    156 					if (buf[i] == ' ')
    157 						last_space = i;
    158 			}
    159 
    160 			if (split_words && last_space != -1) {
    161 				last_space++;
    162 
    163 				fwrite (buf, 1, last_space, stdout);
    164 				memmove (buf, buf+last_space, indx-last_space);
    165 
    166 				indx -= last_space;
    167 				col = 0;
    168 				for (i = 0; i < indx; i++) {
    169 					col = new_column_position (col, buf[i]);
    170 				}
    171 			} else {
    172 				fwrite (buf, 1, indx, stdout);
    173 				col = indx = 0;
    174 			}
    175 			putchar('\n');
    176 
    177 			/* calculate the column position for the next line. */
    178 			col = new_column_position (col, ch);
    179 		}
    180 
    181 		if (indx + 1 > buf_max) {
    182 			/* Allocate buffer in LINE_MAX increments */
    183 			buf_max += 2048;
    184 			if((buf = realloc (buf, buf_max)) == NULL) {
    185 				err (1, "realloc");
    186 				/* NOTREACHED */
    187 			}
    188 		}
    189 		buf[indx++] = ch;
    190 	}
    191 
    192 	if (indx != 0)
    193 		fwrite (buf, 1, indx, stdout);
    194 }
    195 
    196 /*
    197  * calculate the column position
    198  */
    199 static int
    200 new_column_position (int col, int ch)
    201 {
    202 	if (!count_bytes) {
    203 		switch (ch) {
    204 		case '\b':
    205 			if (col > 0)
    206 				--col;
    207 			break;
    208 		case '\r':
    209 			col = 0;
    210 			break;
    211 		case '\t':
    212 			col = (col + 8) & ~7;
    213 			break;
    214 		default:
    215 			++col;
    216 			break;
    217 		}
    218 	} else {
    219 		++col;
    220 	}
    221 
    222 	return col;
    223 }
    224 
    225 static void
    226 usage(void)
    227 	{
    228 	(void)fprintf(stderr,
    229 		    "usage: fold [-bs] [-w width] [file ...]\n");
    230 	exit(1);
    231 	}
    232 
    233