xref: /netbsd-src/usr.bin/fold/fold.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: fold.c,v 1.13 2003/10/16 06:48:03 itojun 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.13 2003/10/16 06:48:03 itojun 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 	char *nbuf;
130 	static int   buf_max = 0;
131 	int ch, col;
132 	int indx;
133 
134 	col = indx = 0;
135 	while ((ch = getchar()) != EOF) {
136 		if (ch == '\n') {
137 			if (indx != 0)
138 				fwrite (buf, 1, indx, stdout);
139 			putchar('\n');
140 			col = indx = 0;
141 			continue;
142 		}
143 
144 		col = new_column_position (col, ch);
145 		if (col > width) {
146 			int i, last_space;
147 
148 #ifdef __GNUC__
149 			last_space = 0;	/* XXX gcc */
150 #endif
151 			if (split_words) {
152 				for (i = 0, last_space = -1; i < indx; i++)
153 					if (buf[i] == ' ')
154 						last_space = i;
155 			}
156 
157 			if (split_words && last_space != -1) {
158 				last_space++;
159 
160 				fwrite (buf, 1, last_space, stdout);
161 				memmove (buf, buf+last_space, indx-last_space);
162 
163 				indx -= last_space;
164 				col = 0;
165 				for (i = 0; i < indx; i++) {
166 					col = new_column_position (col, buf[i]);
167 				}
168 			} else {
169 				fwrite (buf, 1, indx, stdout);
170 				col = indx = 0;
171 			}
172 			putchar('\n');
173 
174 			/* calculate the column position for the next line. */
175 			col = new_column_position (col, ch);
176 		}
177 
178 		if (indx + 1 > buf_max) {
179 			/* Allocate buffer in LINE_MAX increments */
180 			if ((nbuf = realloc (buf, buf_max + 2048)) == NULL) {
181 				err (1, "realloc");
182 				/* NOTREACHED */
183 			}
184 			buf = nbuf;
185 			buf_max += 2048;
186 		}
187 		buf[indx++] = ch;
188 	}
189 
190 	if (indx != 0)
191 		fwrite (buf, 1, indx, stdout);
192 }
193 
194 /*
195  * calculate the column position
196  */
197 static int
198 new_column_position (int col, int ch)
199 {
200 	if (!count_bytes) {
201 		switch (ch) {
202 		case '\b':
203 			if (col > 0)
204 				--col;
205 			break;
206 		case '\r':
207 			col = 0;
208 			break;
209 		case '\t':
210 			col = (col + 8) & ~7;
211 			break;
212 		default:
213 			++col;
214 			break;
215 		}
216 	} else {
217 		++col;
218 	}
219 
220 	return col;
221 }
222 
223 static void
224 usage(void)
225 	{
226 	(void)fprintf(stderr,
227 		    "usage: fold [-bs] [-w width] [file ...]\n");
228 	exit(1);
229 	}
230 
231