seq.c revision 1.10 1 /*
2 * Copyright (c) 2005 The NetBSD Foundation, Inc.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to The NetBSD Foundation
6 * by Brian Ginsbach.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #include <sys/cdefs.h>
31 #ifndef lint
32 __COPYRIGHT("@(#) Copyright (c) 2005\
33 The NetBSD Foundation, Inc. All rights reserved.");
34 __RCSID("$NetBSD: seq.c,v 1.10 2017/10/29 01:28:46 ginsbach Exp $");
35 #endif /* not lint */
36
37 #include <ctype.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <math.h>
41 #include <locale.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #define ZERO '0'
48 #define SPACE ' '
49
50 #define MAX(a, b) (((a) < (b))? (b) : (a))
51 #define ISSIGN(c) ((int)(c) == '-' || (int)(c) == '+')
52 #define ISEXP(c) ((int)(c) == 'e' || (int)(c) == 'E')
53 #define ISODIGIT(c) ((int)(c) >= '0' && (int)(c) <= '7')
54
55 /* Globals */
56
57 const char *decimal_point = "."; /* default */
58 char default_format[] = { "%g" }; /* default */
59
60 /* Prototypes */
61
62 double e_atof(const char *);
63
64 int decimal_places(const char *);
65 int numeric(const char *);
66 int valid_format(const char *);
67
68 char *generate_format(double, double, double, int, char);
69 char *unescape(char *);
70
71 /*
72 * The seq command will print out a numeric sequence from 1, the default,
73 * to a user specified upper limit by 1. The lower bound and increment
74 * maybe indicated by the user on the command line. The sequence can
75 * be either whole, the default, or decimal numbers.
76 */
77 int
78 main(int argc, char *argv[])
79 {
80 int c = 0, errflg = 0;
81 int equalize = 0;
82 double first = 1.0;
83 double last = 0.0;
84 double incr = 0.0;
85 struct lconv *locale;
86 char *fmt = NULL;
87 const char *sep = "\n";
88 const char *term = NULL;
89 char pad = ZERO;
90
91 /* Determine the locale's decimal point. */
92 locale = localeconv();
93 if (locale && locale->decimal_point && locale->decimal_point[0] != '\0')
94 decimal_point = locale->decimal_point;
95
96 /*
97 * Process options, but handle negative numbers separately
98 * least they trip up getopt(3).
99 */
100 while ((optind < argc) && !numeric(argv[optind]) &&
101 (c = getopt(argc, argv, "f:hs:t:w")) != -1) {
102
103 switch (c) {
104 case 'f': /* format (plan9) */
105 fmt = optarg;
106 equalize = 0;
107 break;
108 case 's': /* separator (GNU) */
109 sep = unescape(optarg);
110 break;
111 case 't': /* terminator (new) */
112 term = unescape(optarg);
113 break;
114 case 'w': /* equal width (plan9) */
115 if (!fmt)
116 if (equalize++)
117 pad = SPACE;
118 break;
119 case 'h': /* help (GNU) */
120 default:
121 errflg++;
122 break;
123 }
124 }
125
126 argc -= optind;
127 argv += optind;
128 if (argc < 1 || argc > 3)
129 errflg++;
130
131 if (errflg) {
132 fprintf(stderr,
133 "usage: %s [-w] [-f format] [-s string] [-t string] [first [incr]] last\n",
134 getprogname());
135 exit(1);
136 }
137
138 last = e_atof(argv[argc - 1]);
139
140 if (argc > 1)
141 first = e_atof(argv[0]);
142
143 if (argc > 2) {
144 incr = e_atof(argv[1]);
145 /* Plan 9/GNU don't do zero */
146 if (incr == 0.0)
147 errx(1, "zero %screment", (first < last)? "in" : "de");
148 }
149
150 /* default is one for Plan 9/GNU work alike */
151 if (incr == 0.0)
152 incr = (first < last) ? 1.0 : -1.0;
153
154 if (incr <= 0.0 && first < last)
155 errx(1, "needs positive increment");
156
157 if (incr >= 0.0 && first > last)
158 errx(1, "needs negative decrement");
159
160 if (fmt != NULL) {
161 if (!valid_format(fmt))
162 errx(1, "invalid format string: `%s'", fmt);
163 fmt = unescape(fmt);
164 if (!valid_format(fmt))
165 errx(1, "invalid format string");
166 /*
167 * XXX to be bug for bug compatible with Plan 9 add a
168 * newline if none found at the end of the format string.
169 */
170 } else
171 fmt = generate_format(first, incr, last, equalize, pad);
172
173 if (incr > 0) {
174 for (; first <= last; first += incr) {
175 printf(fmt, first);
176 fputs(sep, stdout);
177 }
178 } else {
179 for (; first >= last; first += incr) {
180 printf(fmt, first);
181 fputs(sep, stdout);
182 }
183 }
184 if (term != NULL)
185 fputs(term, stdout);
186
187 return (0);
188 }
189
190 /*
191 * numeric - verify that string is numeric
192 */
193 int
194 numeric(const char *s)
195 {
196 int seen_decimal_pt, decimal_pt_len;
197
198 /* skip any sign */
199 if (ISSIGN((unsigned char)*s))
200 s++;
201
202 seen_decimal_pt = 0;
203 decimal_pt_len = strlen(decimal_point);
204 while (*s) {
205 if (!isdigit((unsigned char)*s)) {
206 if (!seen_decimal_pt &&
207 strncmp(s, decimal_point, decimal_pt_len) == 0) {
208 s += decimal_pt_len;
209 seen_decimal_pt = 1;
210 continue;
211 }
212 if (ISEXP((unsigned char)*s)) {
213 s++;
214 /* optional sign */
215 if (ISSIGN((unsigned char)*s))
216 s++;
217 continue;
218 }
219 break;
220 }
221 s++;
222 }
223 return (*s == '\0');
224 }
225
226 /*
227 * valid_format - validate user specified format string
228 */
229 int
230 valid_format(const char *fmt)
231 {
232 unsigned conversions = 0;
233
234 while (*fmt != '\0') {
235 /* scan for conversions */
236 if (*fmt != '%') {
237 fmt++;
238 continue;
239 }
240 fmt++;
241
242 /* allow %% but not things like %10% */
243 if (*fmt == '%') {
244 fmt++;
245 continue;
246 }
247
248 /* flags */
249 while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
250 fmt++;
251 }
252
253 /* field width */
254 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
255 fmt++;
256 }
257
258 /* precision */
259 if (*fmt == '.') {
260 fmt++;
261 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
262 fmt++;
263 }
264 }
265
266 /* conversion */
267 switch (*fmt) {
268 case 'A':
269 case 'a':
270 case 'E':
271 case 'e':
272 case 'F':
273 case 'f':
274 case 'G':
275 case 'g':
276 /* floating point formats are accepted */
277 conversions++;
278 break;
279 default:
280 /* anything else is not */
281 return 0;
282 }
283 }
284
285 return (conversions <= 1);
286 }
287
288 /*
289 * unescape - handle C escapes in a string
290 */
291 char *
292 unescape(char *orig)
293 {
294 char c, *cp, *new = orig;
295 int i;
296
297 for (cp = orig; (*orig = *cp); cp++, orig++) {
298 if (*cp != '\\')
299 continue;
300
301 switch (*++cp) {
302 case 'a': /* alert (bell) */
303 *orig = '\a';
304 continue;
305 case 'b': /* backspace */
306 *orig = '\b';
307 continue;
308 case 'e': /* escape */
309 *orig = '\e';
310 continue;
311 case 'f': /* formfeed */
312 *orig = '\f';
313 continue;
314 case 'n': /* newline */
315 *orig = '\n';
316 continue;
317 case 'r': /* carriage return */
318 *orig = '\r';
319 continue;
320 case 't': /* horizontal tab */
321 *orig = '\t';
322 continue;
323 case 'v': /* vertical tab */
324 *orig = '\v';
325 continue;
326 case '\\': /* backslash */
327 *orig = '\\';
328 continue;
329 case '\'': /* single quote */
330 *orig = '\'';
331 continue;
332 case '\"': /* double quote */
333 *orig = '"';
334 continue;
335 case '0':
336 case '1':
337 case '2':
338 case '3': /* octal */
339 case '4':
340 case '5':
341 case '6':
342 case '7': /* number */
343 for (i = 0, c = 0;
344 ISODIGIT((unsigned char)*cp) && i < 3;
345 i++, cp++) {
346 c <<= 3;
347 c |= (*cp - '0');
348 }
349 *orig = c;
350 --cp;
351 continue;
352 case 'x': /* hexadecimal number */
353 cp++; /* skip 'x' */
354 for (i = 0, c = 0;
355 isxdigit((unsigned char)*cp) && i < 2;
356 i++, cp++) {
357 c <<= 4;
358 if (isdigit((unsigned char)*cp))
359 c |= (*cp - '0');
360 else
361 c |= ((toupper((unsigned char)*cp) -
362 'A') + 10);
363 }
364 *orig = c;
365 --cp;
366 continue;
367 default:
368 --cp;
369 break;
370 }
371 }
372
373 return (new);
374 }
375
376 /*
377 * e_atof - convert an ASCII string to a double
378 * exit if string is not a valid double, or if converted value would
379 * cause overflow or underflow
380 */
381 double
382 e_atof(const char *num)
383 {
384 char *endp;
385 double dbl;
386
387 errno = 0;
388 dbl = strtod(num, &endp);
389
390 if (errno == ERANGE)
391 /* under or overflow */
392 err(2, "%s", num);
393 else if (*endp != '\0')
394 /* "junk" left in number */
395 errx(2, "invalid floating point argument: %s", num);
396
397 /* zero shall have no sign */
398 if (dbl == -0.0)
399 dbl = 0;
400 return (dbl);
401 }
402
403 /*
404 * decimal_places - count decimal places in a number (string)
405 */
406 int
407 decimal_places(const char *number)
408 {
409 int places = 0;
410 char *dp;
411
412 /* look for a decimal point */
413 if ((dp = strstr(number, decimal_point))) {
414 dp += strlen(decimal_point);
415
416 while (isdigit((unsigned char)*dp++))
417 places++;
418 }
419 return (places);
420 }
421
422 /*
423 * generate_format - create a format string
424 *
425 * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
426 * when "%g" prints as "%e" (this way no width adjustments are made)
427 */
428 char *
429 generate_format(double first, double incr, double last, int equalize, char pad)
430 {
431 static char buf[256];
432 char cc = '\0';
433 int precision, width1, width2, places;
434
435 if (equalize == 0)
436 return (default_format);
437
438 /* figure out "last" value printed */
439 if (first > last)
440 last = first - incr * floor((first - last) / incr);
441 else
442 last = first + incr * floor((last - first) / incr);
443
444 sprintf(buf, "%g", incr);
445 if (strchr(buf, 'e'))
446 cc = 'e';
447 precision = decimal_places(buf);
448
449 width1 = sprintf(buf, "%g", first);
450 if (strchr(buf, 'e'))
451 cc = 'e';
452 if ((places = decimal_places(buf)))
453 width1 -= (places + strlen(decimal_point));
454
455 precision = MAX(places, precision);
456
457 width2 = sprintf(buf, "%g", last);
458 if (strchr(buf, 'e'))
459 cc = 'e';
460 if ((places = decimal_places(buf)))
461 width2 -= (places + strlen(decimal_point));
462
463 if (precision) {
464 sprintf(buf, "%%%c%d.%d%c", pad,
465 MAX(width1, width2) + (int) strlen(decimal_point) +
466 precision, precision, (cc) ? cc : 'f');
467 } else {
468 sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),
469 (cc) ? cc : 'g');
470 }
471
472 return (buf);
473 }
474