version 8.7
[coreutils.git] / src / seq.c
blob1db7665a3d8bc5752eb31b7f888ef86bd7929371
1 /* seq - print sequence of numbers to standard output.
2 Copyright (C) 1994-2010 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Ulrich Drepper. */
19 #include <config.h>
20 #include <getopt.h>
21 #include <stdio.h>
22 #include <sys/types.h>
24 #include "system.h"
25 #include "c-strtod.h"
26 #include "error.h"
27 #include "quote.h"
28 #include "xstrtod.h"
30 /* Roll our own isfinite rather than using <math.h>, so that we don't
31 have to worry about linking -lm just for isfinite. */
32 #ifndef isfinite
33 # define isfinite(x) ((x) * 0 == 0)
34 #endif
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "seq"
39 #define AUTHORS proper_name ("Ulrich Drepper")
41 /* If true print all number with equal width. */
42 static bool equal_width;
44 /* The string used to separate two numbers. */
45 static char const *separator;
47 /* The string output after all numbers have been output.
48 Usually "\n" or "\0". */
49 static char const terminator[] = "\n";
51 static struct option const long_options[] =
53 { "equal-width", no_argument, NULL, 'w'},
54 { "format", required_argument, NULL, 'f'},
55 { "separator", required_argument, NULL, 's'},
56 {GETOPT_HELP_OPTION_DECL},
57 {GETOPT_VERSION_OPTION_DECL},
58 { NULL, 0, NULL, 0}
61 void
62 usage (int status)
64 if (status != EXIT_SUCCESS)
65 fprintf (stderr, _("Try `%s --help' for more information.\n"),
66 program_name);
67 else
69 printf (_("\
70 Usage: %s [OPTION]... LAST\n\
71 or: %s [OPTION]... FIRST LAST\n\
72 or: %s [OPTION]... FIRST INCREMENT LAST\n\
73 "), program_name, program_name, program_name);
74 fputs (_("\
75 Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
76 \n\
77 -f, --format=FORMAT use printf style floating-point FORMAT\n\
78 -s, --separator=STRING use STRING to separate numbers (default: \\n)\n\
79 -w, --equal-width equalize width by padding with leading zeroes\n\
80 "), stdout);
81 fputs (HELP_OPTION_DESCRIPTION, stdout);
82 fputs (VERSION_OPTION_DESCRIPTION, stdout);
83 fputs (_("\
84 \n\
85 If FIRST or INCREMENT is omitted, it defaults to 1. That is, an\n\
86 omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST.\n\
87 FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
88 INCREMENT is usually positive if FIRST is smaller than LAST, and\n\
89 INCREMENT is usually negative if FIRST is greater than LAST.\n\
90 "), stdout);
91 fputs (_("\
92 FORMAT must be suitable for printing one argument of type `double';\n\
93 it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n\
94 decimal numbers with maximum precision PREC, and to %g otherwise.\n\
95 "), stdout);
96 emit_ancillary_info ();
98 exit (status);
101 /* A command-line operand. */
102 struct operand
104 /* Its value, converted to 'long double'. */
105 long double value;
107 /* Its print width, if it were printed out in a form similar to its
108 input form. An input like "-.1" is treated like "-0.1", and an
109 input like "1." is treated like "1", but otherwise widths are
110 left alone. */
111 size_t width;
113 /* Number of digits after the decimal point, or INT_MAX if the
114 number can't easily be expressed as a fixed-point number. */
115 int precision;
117 typedef struct operand operand;
119 /* Description of what a number-generating format will generate. */
120 struct layout
122 /* Number of bytes before and after the number. */
123 size_t prefix_len;
124 size_t suffix_len;
127 /* Read a long double value from the command line.
128 Return if the string is correct else signal error. */
130 static operand
131 scan_arg (const char *arg)
133 operand ret;
135 if (! xstrtold (arg, NULL, &ret.value, c_strtold))
137 error (0, 0, _("invalid floating point argument: %s"), arg);
138 usage (EXIT_FAILURE);
141 /* We don't output spaces or '+' so don't include in width */
142 while (isspace (to_uchar (*arg)) || *arg == '+')
143 arg++;
145 ret.width = strlen (arg);
146 ret.precision = INT_MAX;
148 if (! arg[strcspn (arg, "xX")] && isfinite (ret.value))
150 char const *decimal_point = strchr (arg, '.');
151 if (! decimal_point)
152 ret.precision = 0;
153 else
155 size_t fraction_len = strcspn (decimal_point + 1, "eE");
156 if (fraction_len <= INT_MAX)
157 ret.precision = fraction_len;
158 ret.width += (fraction_len == 0 /* #. -> # */
159 ? -1
160 : (decimal_point == arg /* .# -> 0.# */
161 || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */
163 char const *e = strchr (arg, 'e');
164 if (! e)
165 e = strchr (arg, 'E');
166 if (e)
168 long exponent = strtol (e + 1, NULL, 10);
169 ret.precision += exponent < 0 ? -exponent : 0;
173 return ret;
176 /* If FORMAT is a valid printf format for a double argument, return
177 its long double equivalent, allocated from dynamic storage, and
178 store into *LAYOUT a description of the output layout; otherwise,
179 report an error and exit. */
181 static char const *
182 long_double_format (char const *fmt, struct layout *layout)
184 size_t i;
185 size_t prefix_len = 0;
186 size_t suffix_len = 0;
187 size_t length_modifier_offset;
188 bool has_L;
190 for (i = 0; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
192 if (!fmt[i])
193 error (EXIT_FAILURE, 0,
194 _("format %s has no %% directive"), quote (fmt));
195 prefix_len++;
198 i++;
199 i += strspn (fmt + i, "-+#0 '");
200 i += strspn (fmt + i, "0123456789");
201 if (fmt[i] == '.')
203 i++;
204 i += strspn (fmt + i, "0123456789");
207 length_modifier_offset = i;
208 has_L = (fmt[i] == 'L');
209 i += has_L;
210 if (fmt[i] == '\0')
211 error (EXIT_FAILURE, 0, _("format %s ends in %%"), quote (fmt));
212 if (! strchr ("efgaEFGA", fmt[i]))
213 error (EXIT_FAILURE, 0,
214 _("format %s has unknown %%%c directive"), quote (fmt), fmt[i]);
216 for (i++; ; i += (fmt[i] == '%') + 1)
217 if (fmt[i] == '%' && fmt[i + 1] != '%')
218 error (EXIT_FAILURE, 0, _("format %s has too many %% directives"),
219 quote (fmt));
220 else if (fmt[i])
221 suffix_len++;
222 else
224 size_t format_size = i + 1;
225 char *ldfmt = xmalloc (format_size + 1);
226 memcpy (ldfmt, fmt, length_modifier_offset);
227 ldfmt[length_modifier_offset] = 'L';
228 strcpy (ldfmt + length_modifier_offset + 1,
229 fmt + length_modifier_offset + has_L);
230 layout->prefix_len = prefix_len;
231 layout->suffix_len = suffix_len;
232 return ldfmt;
236 /* Actually print the sequence of numbers in the specified range, with the
237 given or default stepping and format. */
239 static void
240 print_numbers (char const *fmt, struct layout layout,
241 long double first, long double step, long double last)
243 bool out_of_range = (step < 0 ? first < last : last < first);
245 if (! out_of_range)
247 long double x = first;
248 long double i;
250 for (i = 1; ; i++)
252 long double x0 = x;
253 printf (fmt, x);
254 if (out_of_range)
255 break;
256 x = first + i * step;
257 out_of_range = (step < 0 ? x < last : last < x);
259 if (out_of_range)
261 /* If the number just past LAST prints as a value equal
262 to LAST, and prints differently from the previous
263 number, then print the number. This avoids problems
264 with rounding. For example, with the x86 it causes
265 "seq 0 0.000001 0.000003" to print 0.000003 instead
266 of stopping at 0.000002. */
268 bool print_extra_number = false;
269 long double x_val;
270 char *x_str;
271 int x_strlen;
272 setlocale (LC_NUMERIC, "C");
273 x_strlen = asprintf (&x_str, fmt, x);
274 setlocale (LC_NUMERIC, "");
275 if (x_strlen < 0)
276 xalloc_die ();
277 x_str[x_strlen - layout.suffix_len] = '\0';
279 if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold)
280 && x_val == last)
282 char *x0_str = NULL;
283 if (asprintf (&x0_str, fmt, x0) < 0)
284 xalloc_die ();
285 print_extra_number = !STREQ (x0_str, x_str);
286 free (x0_str);
289 free (x_str);
290 if (! print_extra_number)
291 break;
294 fputs (separator, stdout);
297 fputs (terminator, stdout);
301 /* Return the default format given FIRST, STEP, and LAST. */
302 static char const *
303 get_default_format (operand first, operand step, operand last)
305 static char format_buf[sizeof "%0.Lf" + 2 * INT_STRLEN_BOUND (int)];
307 int prec = MAX (first.precision, step.precision);
309 if (prec != INT_MAX && last.precision != INT_MAX)
311 if (equal_width)
313 /* increase first_width by any increased precision in step */
314 size_t first_width = first.width + (prec - first.precision);
315 /* adjust last_width to use precision from first/step */
316 size_t last_width = last.width + (prec - last.precision);
317 if (last.precision && prec == 0)
318 last_width--; /* don't include space for '.' */
319 if (last.precision == 0 && prec)
320 last_width++; /* include space for '.' */
321 size_t width = MAX (first_width, last_width);
322 if (width <= INT_MAX)
324 int w = width;
325 sprintf (format_buf, "%%0%d.%dLf", w, prec);
326 return format_buf;
329 else
331 sprintf (format_buf, "%%.%dLf", prec);
332 return format_buf;
336 return "%Lg";
340 main (int argc, char **argv)
342 int optc;
343 operand first = { 1, 1, 0 };
344 operand step = { 1, 1, 0 };
345 operand last;
346 struct layout layout = { 0, 0 };
348 /* The printf(3) format used for output. */
349 char const *format_str = NULL;
351 initialize_main (&argc, &argv);
352 set_program_name (argv[0]);
353 setlocale (LC_ALL, "");
354 bindtextdomain (PACKAGE, LOCALEDIR);
355 textdomain (PACKAGE);
357 atexit (close_stdout);
359 equal_width = false;
360 separator = "\n";
362 /* We have to handle negative numbers in the command line but this
363 conflicts with the command line arguments. So explicitly check first
364 whether the next argument looks like a negative number. */
365 while (optind < argc)
367 if (argv[optind][0] == '-'
368 && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc)))
370 /* means negative number */
371 break;
374 optc = getopt_long (argc, argv, "+f:s:w", long_options, NULL);
375 if (optc == -1)
376 break;
378 switch (optc)
380 case 'f':
381 format_str = optarg;
382 break;
384 case 's':
385 separator = optarg;
386 break;
388 case 'w':
389 equal_width = true;
390 break;
392 case_GETOPT_HELP_CHAR;
394 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
396 default:
397 usage (EXIT_FAILURE);
401 if (argc - optind < 1)
403 error (0, 0, _("missing operand"));
404 usage (EXIT_FAILURE);
407 if (3 < argc - optind)
409 error (0, 0, _("extra operand %s"), quote (argv[optind + 3]));
410 usage (EXIT_FAILURE);
413 if (format_str)
414 format_str = long_double_format (format_str, &layout);
416 last = scan_arg (argv[optind++]);
418 if (optind < argc)
420 first = last;
421 last = scan_arg (argv[optind++]);
423 if (optind < argc)
425 step = last;
426 last = scan_arg (argv[optind++]);
430 if (format_str != NULL && equal_width)
432 error (0, 0, _("\
433 format string may not be specified when printing equal width strings"));
434 usage (EXIT_FAILURE);
437 if (format_str == NULL)
438 format_str = get_default_format (first, step, last);
440 print_numbers (format_str, layout, first.value, step.value, last.value);
442 exit (EXIT_SUCCESS);