]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/seq/seq.c
MFC r333122: seq(1): Provide some long options
[FreeBSD/FreeBSD.git] / usr.bin / seq / seq.c
1 /*      $NetBSD: seq.c,v 1.7 2010/05/27 08:40:19 dholland Exp $ */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
4  *
5  * Copyright (c) 2005 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Brian Ginsbach.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
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.
19  *
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.
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <getopt.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 static const char *decimal_point = "."; /* default */
58 static char default_format[] = { "%g" };        /* default */
59
60 /* Prototypes */
61
62 static double e_atof(const char *);
63
64 static int decimal_places(const char *);
65 static int numeric(const char *);
66 static int valid_format(const char *);
67
68 static char *generate_format(double, double, double, int, char);
69 static char *unescape(char *);
70
71 static const struct option long_opts[] =
72 {
73         {"format",      required_argument,      NULL, 'f'},
74         {"separator",   required_argument,      NULL, 's'},
75         {"terminator",  required_argument,      NULL, 't'},
76         {"equal-width", no_argument,            NULL, 'w'},
77         {NULL,          no_argument,            NULL, 0}
78 };
79
80 /*
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.
85  */
86 int
87 main(int argc, char *argv[])
88 {
89         int c = 0, errflg = 0;
90         int equalize = 0;
91         double first = 1.0;
92         double last = 0.0;
93         double incr = 0.0;
94         struct lconv *locale;
95         char *fmt = NULL;
96         const char *sep = "\n";
97         const char *term = NULL;
98         char pad = ZERO;
99
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;
104
105         /*
106          * Process options, but handle negative numbers separately
107          * least they trip up getopt(3).
108          */
109         while ((optind < argc) && !numeric(argv[optind]) &&
110             (c = getopt_long(argc, argv, "+f:hs:t:w", long_opts, NULL)) != -1) {
111
112                 switch (c) {
113                 case 'f':       /* format (plan9) */
114                         fmt = optarg;
115                         equalize = 0;
116                         break;
117                 case 's':       /* separator (GNU) */
118                         sep = unescape(optarg);
119                         break;
120                 case 't':       /* terminator (new) */
121                         term = unescape(optarg);
122                         break;
123                 case 'w':       /* equal width (plan9) */
124                         if (!fmt)
125                                 if (equalize++)
126                                         pad = SPACE;
127                         break;
128                 case 'h':       /* help (GNU) */
129                 default:
130                         errflg++;
131                         break;
132                 }
133         }
134
135         argc -= optind;
136         argv += optind;
137         if (argc < 1 || argc > 3)
138                 errflg++;
139
140         if (errflg) {
141                 fprintf(stderr,
142                     "usage: %s [-w] [-f format] [-s string] [-t string] [first [incr]] last\n",
143                     getprogname());
144                 exit(1);
145         }
146
147         last = e_atof(argv[argc - 1]);
148
149         if (argc > 1)
150                 first = e_atof(argv[0]);
151         
152         if (argc > 2) {
153                 incr = e_atof(argv[1]);
154                 /* Plan 9/GNU don't do zero */
155                 if (incr == 0.0)
156                         errx(1, "zero %screment", (first < last)? "in" : "de");
157         }
158
159         /* default is one for Plan 9/GNU work alike */
160         if (incr == 0.0)
161                 incr = (first < last) ? 1.0 : -1.0;
162
163         if (incr <= 0.0 && first < last)
164                 errx(1, "needs positive increment");
165
166         if (incr >= 0.0 && first > last)
167                 errx(1, "needs negative decrement");
168
169         if (fmt != NULL) {
170                 if (!valid_format(fmt))
171                         errx(1, "invalid format string: `%s'", fmt);
172                 fmt = unescape(fmt);
173                 if (!valid_format(fmt))
174                         errx(1, "invalid format string");
175                 /*
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.
178                  */
179         } else
180                 fmt = generate_format(first, incr, last, equalize, pad);
181
182         if (incr > 0) {
183                 for (; first <= last; first += incr) {
184                         printf(fmt, first);
185                         fputs(sep, stdout);
186                 }
187         } else {
188                 for (; first >= last; first += incr) {
189                         printf(fmt, first);
190                         fputs(sep, stdout);
191                 }
192         }
193         if (term != NULL)
194                 fputs(term, stdout);
195
196         return (0);
197 }
198
199 /*
200  * numeric - verify that string is numeric
201  */
202 static int
203 numeric(const char *s)
204 {
205         int seen_decimal_pt, decimal_pt_len;
206
207         /* skip any sign */
208         if (ISSIGN((unsigned char)*s))
209                 s++;
210
211         seen_decimal_pt = 0;
212         decimal_pt_len = strlen(decimal_point);
213         while (*s) {
214                 if (!isdigit((unsigned char)*s)) {
215                         if (!seen_decimal_pt &&
216                             strncmp(s, decimal_point, decimal_pt_len) == 0) {
217                                 s += decimal_pt_len;
218                                 seen_decimal_pt = 1;
219                                 continue;
220                         }
221                         if (ISEXP((unsigned char)*s)) {
222                                 s++;
223                                 if (ISSIGN((unsigned char)*s) ||
224                                     isdigit((unsigned char)*s)) {
225                                         s++;
226                                         continue;
227                                 }
228                         }
229                         break;
230                 }
231                 s++;
232         }
233         return (*s == '\0');
234 }
235
236 /*
237  * valid_format - validate user specified format string
238  */
239 static int
240 valid_format(const char *fmt)
241 {
242         unsigned conversions = 0;
243
244         while (*fmt != '\0') {
245                 /* scan for conversions */
246                 if (*fmt != '%') {
247                         fmt++;
248                         continue;
249                 }
250                 fmt++;
251
252                 /* allow %% but not things like %10% */
253                 if (*fmt == '%') {
254                         fmt++;
255                         continue;
256                 }
257
258                 /* flags */
259                 while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
260                         fmt++;
261                 }
262
263                 /* field width */
264                 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
265                         fmt++;
266                 }
267
268                 /* precision */
269                 if (*fmt == '.') {
270                         fmt++;
271                         while (*fmt != '\0' && strchr("0123456789", *fmt)) {
272                                 fmt++;
273                         }
274                 }
275
276                 /* conversion */
277                 switch (*fmt) {
278                     case 'A':
279                     case 'a':
280                     case 'E':
281                     case 'e':
282                     case 'F':
283                     case 'f':
284                     case 'G':
285                     case 'g':
286                         /* floating point formats are accepted */
287                         conversions++;
288                         break;
289                     default:
290                         /* anything else is not */
291                         return 0;
292                 }
293         }
294
295         return (conversions <= 1);
296 }
297
298 /*
299  * unescape - handle C escapes in a string
300  */
301 static char *
302 unescape(char *orig)
303 {
304         char c, *cp, *new = orig;
305         int i;
306
307         for (cp = orig; (*orig = *cp); cp++, orig++) {
308                 if (*cp != '\\')
309                         continue;
310
311                 switch (*++cp) {
312                 case 'a':       /* alert (bell) */
313                         *orig = '\a';
314                         continue;
315                 case 'b':       /* backspace */
316                         *orig = '\b';
317                         continue;
318                 case 'e':       /* escape */
319                         *orig = '\e';
320                         continue;
321                 case 'f':       /* formfeed */
322                         *orig = '\f';
323                         continue;
324                 case 'n':       /* newline */
325                         *orig = '\n';
326                         continue;
327                 case 'r':       /* carriage return */
328                         *orig = '\r';
329                         continue;
330                 case 't':       /* horizontal tab */
331                         *orig = '\t';
332                         continue;
333                 case 'v':       /* vertical tab */
334                         *orig = '\v';
335                         continue;
336                 case '\\':      /* backslash */
337                         *orig = '\\';
338                         continue;
339                 case '\'':      /* single quote */
340                         *orig = '\'';
341                         continue;
342                 case '\"':      /* double quote */
343                         *orig = '"';
344                         continue;
345                 case '0':
346                 case '1':
347                 case '2':
348                 case '3':       /* octal */
349                 case '4':
350                 case '5':
351                 case '6':
352                 case '7':       /* number */
353                         for (i = 0, c = 0;
354                              ISODIGIT((unsigned char)*cp) && i < 3;
355                              i++, cp++) {
356                                 c <<= 3;
357                                 c |= (*cp - '0');
358                         }
359                         *orig = c;
360                         --cp;
361                         continue;
362                 case 'x':       /* hexadecimal number */
363                         cp++;   /* skip 'x' */
364                         for (i = 0, c = 0;
365                              isxdigit((unsigned char)*cp) && i < 2;
366                              i++, cp++) {
367                                 c <<= 4;
368                                 if (isdigit((unsigned char)*cp))
369                                         c |= (*cp - '0');
370                                 else
371                                         c |= ((toupper((unsigned char)*cp) -
372                                             'A') + 10);
373                         }
374                         *orig = c;
375                         --cp;
376                         continue;
377                 default:
378                         --cp;
379                         break;
380                 }
381         }
382
383         return (new);
384 }
385
386 /*
387  * e_atof - convert an ASCII string to a double
388  *      exit if string is not a valid double, or if converted value would
389  *      cause overflow or underflow
390  */
391 static double
392 e_atof(const char *num)
393 {
394         char *endp;
395         double dbl;
396
397         errno = 0;
398         dbl = strtod(num, &endp);
399
400         if (errno == ERANGE)
401                 /* under or overflow */
402                 err(2, "%s", num);
403         else if (*endp != '\0')
404                 /* "junk" left in number */
405                 errx(2, "invalid floating point argument: %s", num);
406
407         /* zero shall have no sign */
408         if (dbl == -0.0)
409                 dbl = 0;
410         return (dbl);
411 }
412
413 /*
414  * decimal_places - count decimal places in a number (string)
415  */
416 static int
417 decimal_places(const char *number)
418 {
419         int places = 0;
420         char *dp;
421
422         /* look for a decimal point */
423         if ((dp = strstr(number, decimal_point))) {
424                 dp += strlen(decimal_point);
425
426                 while (isdigit((unsigned char)*dp++))
427                         places++;
428         }
429         return (places);
430 }
431
432 /*
433  * generate_format - create a format string
434  *
435  * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
436  * when "%g" prints as "%e" (this way no width adjustments are made)
437  */
438 static char *
439 generate_format(double first, double incr, double last, int equalize, char pad)
440 {
441         static char buf[256];
442         char cc = '\0';
443         int precision, width1, width2, places;
444
445         if (equalize == 0)
446                 return (default_format);
447
448         /* figure out "last" value printed */
449         if (first > last)
450                 last = first - incr * floor((first - last) / incr);
451         else
452                 last = first + incr * floor((last - first) / incr);
453
454         sprintf(buf, "%g", incr);
455         if (strchr(buf, 'e'))
456                 cc = 'e';
457         precision = decimal_places(buf);
458
459         width1 = sprintf(buf, "%g", first);
460         if (strchr(buf, 'e'))
461                 cc = 'e';
462         if ((places = decimal_places(buf)))
463                 width1 -= (places + strlen(decimal_point));
464
465         precision = MAX(places, precision);
466
467         width2 = sprintf(buf, "%g", last);
468         if (strchr(buf, 'e'))
469                 cc = 'e';
470         if ((places = decimal_places(buf)))
471                 width2 -= (places + strlen(decimal_point));
472
473         if (precision) {
474                 sprintf(buf, "%%%c%d.%d%c", pad,
475                     MAX(width1, width2) + (int) strlen(decimal_point) +
476                     precision, precision, (cc) ? cc : 'f');
477         } else {
478                 sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),
479                     (cc) ? cc : 'g');
480         }
481
482         return (buf);
483 }