1 /* $NetBSD: seq.c,v 1.7 2010/05/27 08:40:19 dholland Exp $ */
3 * SPDX-License-Identifier: BSD-2-Clause
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>
48 #define MAX(a, b) (((a) < (b))? (b) : (a))
49 #define ISSIGN(c) ((int)(c) == '-' || (int)(c) == '+')
50 #define ISEXP(c) ((int)(c) == 'e' || (int)(c) == 'E')
51 #define ISODIGIT(c) ((int)(c) >= '0' && (int)(c) <= '7')
55 static const char *decimal_point = "."; /* default */
56 static char default_format[] = { "%g" }; /* default */
58 static const struct option long_opts[] = {
59 {"format", required_argument, NULL, 'f'},
60 {"separator", required_argument, NULL, 's'},
61 {"terminator", required_argument, NULL, 't'},
62 {"equal-width", no_argument, NULL, 'w'},
63 {NULL, no_argument, NULL, 0}
68 static double e_atof(const char *);
70 static int decimal_places(const char *);
71 static int numeric(const char *);
72 static int valid_format(const char *);
74 static char *generate_format(double, double, double, int, char);
75 static char *unescape(char *);
78 * The seq command will print out a numeric sequence from 1, the default,
79 * to a user specified upper limit by 1. The lower bound and increment
80 * maybe indicated by the user on the command line. The sequence can
81 * be either whole, the default, or decimal numbers.
84 main(int argc, char *argv[])
86 const char *sep, *term;
88 char pad, *fmt, *cur_print, *last_print, *prev_print;
89 double first, last, incr, prev, cur, step;
90 int c, errflg, equalize;
95 last = incr = prev = 0.0;
96 c = errflg = equalize = 0;
100 /* Determine the locale's decimal point. */
101 locale = localeconv();
102 if (locale && locale->decimal_point && locale->decimal_point[0] != '\0')
103 decimal_point = locale->decimal_point;
106 * Process options, but handle negative numbers separately
107 * least they trip up getopt(3).
109 while ((optind < argc) && !numeric(argv[optind]) &&
110 (c = getopt_long(argc, argv, "+f:hs:t:w", long_opts, NULL)) != -1) {
113 case 'f': /* format (plan9) */
117 case 's': /* separator (GNU) */
118 sep = unescape(optarg);
120 case 't': /* terminator (new) */
121 term = unescape(optarg);
123 case 'w': /* equal width (plan9) */
128 case 'h': /* help (GNU) */
137 if (argc < 1 || argc > 3)
142 "usage: %s [-w] [-f format] [-s string] [-t string] [first [incr]] last\n",
147 last = e_atof(argv[argc - 1]);
150 first = e_atof(argv[0]);
153 incr = e_atof(argv[1]);
154 /* Plan 9/GNU don't do zero */
156 errx(1, "zero %screment", (first < last) ? "in" : "de");
159 /* default is one for Plan 9/GNU work alike */
161 incr = (first < last) ? 1.0 : -1.0;
163 if (incr <= 0.0 && first < last)
164 errx(1, "needs positive increment");
166 if (incr >= 0.0 && first > last)
167 errx(1, "needs negative decrement");
170 if (!valid_format(fmt))
171 errx(1, "invalid format string: `%s'", fmt);
173 if (!valid_format(fmt))
174 errx(1, "invalid format string");
176 * XXX to be bug for bug compatible with Plan 9 add a
177 * newline if none found at the end of the format string.
180 fmt = generate_format(first, incr, last, equalize, pad);
182 for (step = 1, cur = first; incr > 0 ? cur <= last : cur >= last;
183 cur = first + incr * step++) {
191 * Did we miss the last value of the range in the loop above?
193 * We might have, so check if the printable version of the last
194 * computed value ('cur') and desired 'last' value are equal. If they
195 * are equal after formatting truncation, but 'cur' and 'prev' are not
196 * equal, it means the exit condition of the loop held true due to a
197 * rounding error and we still need to print 'last'.
199 if (asprintf(&cur_print, fmt, cur) < 0 ||
200 asprintf(&last_print, fmt, last) < 0 ||
201 asprintf(&prev_print, fmt, prev) < 0) {
204 if (strcmp(cur_print, last_print) == 0 &&
205 strcmp(cur_print, prev_print) != 0) {
207 fputs(last_print, stdout);
224 * numeric - verify that string is numeric
227 numeric(const char *s)
229 int seen_decimal_pt, decimal_pt_len;
232 if (ISSIGN((unsigned char)*s))
236 decimal_pt_len = strlen(decimal_point);
238 if (!isdigit((unsigned char)*s)) {
239 if (!seen_decimal_pt &&
240 strncmp(s, decimal_point, decimal_pt_len) == 0) {
245 if (ISEXP((unsigned char)*s)) {
247 if (ISSIGN((unsigned char)*s) ||
248 isdigit((unsigned char)*s)) {
261 * valid_format - validate user specified format string
264 valid_format(const char *fmt)
266 unsigned conversions = 0;
268 while (*fmt != '\0') {
269 /* scan for conversions */
276 /* allow %% but not things like %10% */
283 while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
288 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
295 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
310 /* floating point formats are accepted */
314 /* anything else is not */
319 /* PR 236347 -- user format strings must have a conversion */
320 return (conversions == 1);
324 * unescape - handle C escapes in a string
329 char c, *cp, *new = orig;
332 for (cp = orig; (*orig = *cp); cp++, orig++) {
337 case 'a': /* alert (bell) */
340 case 'b': /* backspace */
343 case 'e': /* escape */
346 case 'f': /* formfeed */
349 case 'n': /* newline */
352 case 'r': /* carriage return */
355 case 't': /* horizontal tab */
358 case 'v': /* vertical tab */
361 case '\\': /* backslash */
364 case '\'': /* single quote */
367 case '\"': /* double quote */
373 case '3': /* octal */
377 case '7': /* number */
379 ISODIGIT((unsigned char)*cp) && i < 3;
387 case 'x': /* hexadecimal number */
390 isxdigit((unsigned char)*cp) && i < 2;
393 if (isdigit((unsigned char)*cp))
396 c |= ((toupper((unsigned char)*cp) -
412 * e_atof - convert an ASCII string to a double
413 * exit if string is not a valid double, or if converted value would
414 * cause overflow or underflow
417 e_atof(const char *num)
423 dbl = strtod(num, &endp);
426 /* under or overflow */
428 else if (*endp != '\0')
429 /* "junk" left in number */
430 errx(2, "invalid floating point argument: %s", num);
432 /* zero shall have no sign */
439 * decimal_places - count decimal places in a number (string)
442 decimal_places(const char *number)
447 /* look for a decimal point */
448 if ((dp = strstr(number, decimal_point))) {
449 dp += strlen(decimal_point);
451 while (isdigit((unsigned char)*dp++))
458 * generate_format - create a format string
460 * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
461 * when "%g" prints as "%e" (this way no width adjustments are made)
464 generate_format(double first, double incr, double last, int equalize, char pad)
466 static char buf[256];
468 int precision, width1, width2, places;
471 return (default_format);
473 /* figure out "last" value printed */
475 last = first - incr * floor((first - last) / incr);
477 last = first + incr * floor((last - first) / incr);
479 sprintf(buf, "%g", incr);
480 if (strchr(buf, 'e'))
482 precision = decimal_places(buf);
484 width1 = sprintf(buf, "%g", first);
485 if (strchr(buf, 'e'))
487 if ((places = decimal_places(buf)))
488 width1 -= (places + strlen(decimal_point));
490 precision = MAX(places, precision);
492 width2 = sprintf(buf, "%g", last);
493 if (strchr(buf, 'e'))
495 if ((places = decimal_places(buf)))
496 width2 -= (places + strlen(decimal_point));
499 sprintf(buf, "%%%c%d.%d%c", pad,
500 MAX(width1, width2) + (int) strlen(decimal_point) +
501 precision, precision, (cc) ? cc : 'f');
503 sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),