1 /* $NetBSD: seq.c,v 1.7 2010/05/27 08:40:19 dholland Exp $ */
3 * SPDX-License-Identifier: BSD-2-Clause-NetBSD
5 * Copyright (c) 2005 The NetBSD Foundation, Inc.
8 * This code is derived from software contributed to The NetBSD Foundation
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
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')
57 static const char *decimal_point = "."; /* default */
58 static char default_format[] = { "%g" }; /* default */
60 static const struct option long_opts[] =
62 {"format", required_argument, NULL, 'f'},
63 {"separator", required_argument, NULL, 's'},
64 {"terminator", required_argument, NULL, 't'},
65 {"equal-width", no_argument, NULL, 'w'},
66 {NULL, no_argument, NULL, 0}
71 static double e_atof(const char *);
73 static int decimal_places(const char *);
74 static int numeric(const char *);
75 static int valid_format(const char *);
77 static char *generate_format(double, double, double, int, char);
78 static char *unescape(char *);
81 * The seq command will print out a numeric sequence from 1, the default,
82 * to a user specified upper limit by 1. The lower bound and increment
83 * maybe indicated by the user on the command line. The sequence can
84 * be either whole, the default, or decimal numbers.
87 main(int argc, char *argv[])
89 const char *sep, *term;
91 char pad, *fmt, *cur_print, *last_print;
92 double first, last, incr, last_shown_value, cur, step;
93 int c, errflg, equalize;
98 last = incr = last_shown_value = 0.0;
99 c = errflg = equalize = 0;
103 /* Determine the locale's decimal point. */
104 locale = localeconv();
105 if (locale && locale->decimal_point && locale->decimal_point[0] != '\0')
106 decimal_point = locale->decimal_point;
109 * Process options, but handle negative numbers separately
110 * least they trip up getopt(3).
112 while ((optind < argc) && !numeric(argv[optind]) &&
113 (c = getopt_long(argc, argv, "+f:hs:t:w", long_opts, NULL)) != -1) {
116 case 'f': /* format (plan9) */
120 case 's': /* separator (GNU) */
121 sep = unescape(optarg);
123 case 't': /* terminator (new) */
124 term = unescape(optarg);
126 case 'w': /* equal width (plan9) */
131 case 'h': /* help (GNU) */
140 if (argc < 1 || argc > 3)
145 "usage: %s [-w] [-f format] [-s string] [-t string] [first [incr]] last\n",
150 last = e_atof(argv[argc - 1]);
153 first = e_atof(argv[0]);
156 incr = e_atof(argv[1]);
157 /* Plan 9/GNU don't do zero */
159 errx(1, "zero %screment", (first < last)? "in" : "de");
162 /* default is one for Plan 9/GNU work alike */
164 incr = (first < last) ? 1.0 : -1.0;
166 if (incr <= 0.0 && first < last)
167 errx(1, "needs positive increment");
169 if (incr >= 0.0 && first > last)
170 errx(1, "needs negative decrement");
173 if (!valid_format(fmt))
174 errx(1, "invalid format string: `%s'", fmt);
176 if (!valid_format(fmt))
177 errx(1, "invalid format string");
179 * XXX to be bug for bug compatible with Plan 9 add a
180 * newline if none found at the end of the format string.
183 fmt = generate_format(first, incr, last, equalize, pad);
185 for (step = 1, cur = first; incr > 0 ? cur <= last : cur >= last;
186 cur = first + incr * step++) {
189 last_shown_value = cur;
193 * Did we miss the last value of the range in the loop above?
195 * We might have, so check if the printable version of the last
196 * computed value ('cur') and desired 'last' value are equal. If they
197 * are equal after formatting truncation, but 'cur' and
198 * 'last_shown_value' are not equal, it means the exit condition of the
199 * loop held true due to a rounding error and we still need to print
202 if (asprintf(&cur_print, fmt, cur) < 0) {
205 if (asprintf(&last_print, fmt, last) < 0) {
208 if (strcmp(cur_print, last_print) == 0 && cur != last_shown_value) {
209 fputs(last_print, stdout);
222 * numeric - verify that string is numeric
225 numeric(const char *s)
227 int seen_decimal_pt, decimal_pt_len;
230 if (ISSIGN((unsigned char)*s))
234 decimal_pt_len = strlen(decimal_point);
236 if (!isdigit((unsigned char)*s)) {
237 if (!seen_decimal_pt &&
238 strncmp(s, decimal_point, decimal_pt_len) == 0) {
243 if (ISEXP((unsigned char)*s)) {
245 if (ISSIGN((unsigned char)*s) ||
246 isdigit((unsigned char)*s)) {
259 * valid_format - validate user specified format string
262 valid_format(const char *fmt)
264 unsigned conversions = 0;
266 while (*fmt != '\0') {
267 /* scan for conversions */
274 /* allow %% but not things like %10% */
281 while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
286 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
293 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
308 /* floating point formats are accepted */
312 /* anything else is not */
317 /* PR 236347 -- user format strings must have a conversion */
318 return (conversions == 1);
322 * unescape - handle C escapes in a string
327 char c, *cp, *new = orig;
330 for (cp = orig; (*orig = *cp); cp++, orig++) {
335 case 'a': /* alert (bell) */
338 case 'b': /* backspace */
341 case 'e': /* escape */
344 case 'f': /* formfeed */
347 case 'n': /* newline */
350 case 'r': /* carriage return */
353 case 't': /* horizontal tab */
356 case 'v': /* vertical tab */
359 case '\\': /* backslash */
362 case '\'': /* single quote */
365 case '\"': /* double quote */
371 case '3': /* octal */
375 case '7': /* number */
377 ISODIGIT((unsigned char)*cp) && i < 3;
385 case 'x': /* hexadecimal number */
388 isxdigit((unsigned char)*cp) && i < 2;
391 if (isdigit((unsigned char)*cp))
394 c |= ((toupper((unsigned char)*cp) -
410 * e_atof - convert an ASCII string to a double
411 * exit if string is not a valid double, or if converted value would
412 * cause overflow or underflow
415 e_atof(const char *num)
421 dbl = strtod(num, &endp);
424 /* under or overflow */
426 else if (*endp != '\0')
427 /* "junk" left in number */
428 errx(2, "invalid floating point argument: %s", num);
430 /* zero shall have no sign */
437 * decimal_places - count decimal places in a number (string)
440 decimal_places(const char *number)
445 /* look for a decimal point */
446 if ((dp = strstr(number, decimal_point))) {
447 dp += strlen(decimal_point);
449 while (isdigit((unsigned char)*dp++))
456 * generate_format - create a format string
458 * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
459 * when "%g" prints as "%e" (this way no width adjustments are made)
462 generate_format(double first, double incr, double last, int equalize, char pad)
464 static char buf[256];
466 int precision, width1, width2, places;
469 return (default_format);
471 /* figure out "last" value printed */
473 last = first - incr * floor((first - last) / incr);
475 last = first + incr * floor((last - first) / incr);
477 sprintf(buf, "%g", incr);
478 if (strchr(buf, 'e'))
480 precision = decimal_places(buf);
482 width1 = sprintf(buf, "%g", first);
483 if (strchr(buf, 'e'))
485 if ((places = decimal_places(buf)))
486 width1 -= (places + strlen(decimal_point));
488 precision = MAX(places, precision);
490 width2 = sprintf(buf, "%g", last);
491 if (strchr(buf, 'e'))
493 if ((places = decimal_places(buf)))
494 width2 -= (places + strlen(decimal_point));
497 sprintf(buf, "%%%c%d.%d%c", pad,
498 MAX(width1, width2) + (int) strlen(decimal_point) +
499 precision, precision, (cc) ? cc : 'f');
501 sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),