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