1 /* printf - format and print data
2 Copyright (C) 1990-2003, 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Usage: printf format [argument...]
20 A front end to the printf function that lets it be used from the shell.
28 \c = produce no further output
34 \ooo = octal number (ooo is 1 to 3 digits)
35 \xhh = hexadecimal number (hhh is 1 to 2 digits)
36 \uhhhh = 16-bit Unicode character (hhhh is 4 digits)
37 \Uhhhhhhhh = 32-bit Unicode character (hhhhhhhh is 8 digits)
41 %b = print an argument string, interpreting backslash escapes,
42 except that octal escapes are of the form \0 or \0ooo.
44 The `format' argument is re-used as many times as necessary
45 to convert all of the given arguments.
47 David MacKenzie <djm@gnu.ai.mit.edu> */
51 #include <sys/types.h>
55 #include "long-options.h"
57 #include "unicodeio.h"
59 /* The official name of this program (e.g., no `g' prefix). */
60 #define PROGRAM_NAME "printf"
62 #define WRITTEN_BY _("Written by David MacKenzie.")
67 unsigned long int strtoul ();
70 #define isodigit(c) ((c) >= '0' && (c) <= '7')
71 #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \
72 (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0')
73 #define octtobin(c) ((c) - '0')
75 /* A value for field_width or precision that indicates it was not specified. */
76 #define UNSPECIFIED INT_MIN
78 /* The value to return to the calling program. */
79 static int exit_status;
81 /* Non-zero if the POSIXLY_CORRECT environment variable is set. */
82 static int posixly_correct;
84 /* This message appears in N_() here rather than just in _() below because
85 the sole use would have been in a #define. */
86 static char *const cfcc_msg =
87 N_("warning: %s: character(s) following character constant have been ignored");
89 /* The name this program was run with. */
96 fprintf (stderr, _("Try `%s --help' for more information.\n"),
101 Usage: %s FORMAT [ARGUMENT]...\n\
104 program_name, program_name);
106 Print ARGUMENT(s) according to FORMAT.\n\
109 fputs (HELP_OPTION_DESCRIPTION, stdout);
110 fputs (VERSION_OPTION_DESCRIPTION, stdout);
113 FORMAT controls the output as in C printf. Interpreted sequences are:\n\
116 \\NNN character with octal value NNN (1 to 3 digits)\n\
122 \\c produce no further output\n\
127 \\r carriage return\n\
128 \\t horizontal tab\n\
132 \\xNN byte with hexadecimal value NN (1 to 2 digits)\n\
134 \\uNNNN character with hexadecimal value NNNN (4 digits)\n\
135 \\UNNNNNNNN character with hexadecimal value NNNNNNNN (8 digits)\n\
139 %b ARGUMENT as a string with `\\' escapes interpreted,\n\
140 except that octal escapes are of the form \\0 or \\0NNN\n\
142 and all C format specifications ending with one of diouxXfeEgGcs, with\n\
143 ARGUMENTs converted to proper type first. Variable widths are handled.\n\
145 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
151 verify (const char *s, const char *end)
155 error (0, errno, "%s", s);
161 error (0, 0, _("%s: expected a numeric value"), s);
163 error (0, 0, _("%s: value not completely converted"), s);
168 #define STRTOX(TYPE, FUNC_NAME, LIB_FUNC_EXPR) \
176 if (*s == '\"' || *s == '\'') \
178 val = *(unsigned char *) ++s; \
179 /* If POSIXLY_CORRECT is not set, then give a warning that there \
180 are characters following the character constant and that GNU \
181 printf is ignoring those characters. If POSIXLY_CORRECT *is* \
182 set, then don't give the warning. */ \
183 if (*++s != 0 && !posixly_correct) \
184 error (0, 0, _(cfcc_msg), s); \
189 val = LIB_FUNC_EXPR; \
195 STRTOX (unsigned long int, xstrtoul, (strtoul (s, &end, 0)))
196 STRTOX (long int, xstrtol, (strtol (s, &end, 0)))
197 STRTOX (double, xstrtod, (strtod (s, &end)))
199 /* Output a single-character \ escape. */
202 print_esc_char (int c)
206 case 'a': /* Alert. */
209 case 'b': /* Backspace. */
212 case 'c': /* Cancel the rest of the output. */
215 case 'f': /* Form feed. */
218 case 'n': /* New line. */
221 case 'r': /* Carriage return. */
224 case 't': /* Horizontal tab. */
227 case 'v': /* Vertical tab. */
236 /* Print a \ escape sequence starting at ESCSTART.
237 Return the number of characters in the escape sequence
238 besides the backslash.
239 If OCTAL_0 is nonzero, octal escapes are of the form \0ooo, where o
240 is an octal digit; otherwise they are of the form \ooo. */
243 print_esc (const char *escstart, bool octal_0)
245 register const char *p = escstart + 1;
246 int esc_value = 0; /* Value of \nnn escape. */
247 int esc_length; /* Length of \nnn escape. */
249 if (!posixly_correct && *p == 'x')
251 /* A hexadecimal \xhh escape sequence must have 1 or 2 hex. digits. */
252 for (esc_length = 0, ++p;
253 esc_length < 2 && ISXDIGIT (*p);
255 esc_value = esc_value * 16 + hextobin (*p);
257 error (EXIT_FAILURE, 0, _("missing hexadecimal number in escape"));
260 else if (isodigit (*p))
262 /* Parse \0ooo (if octal_0 && *p == '0') or \ooo (otherwise).
263 Allow \ooo if octal_0 && *p != '0'; this is an undocumented
264 extension to POSIX that is compatible with Bash 2.05b. */
265 for (esc_length = 0, p += octal_0 && *p == '0';
266 esc_length < 3 && isodigit (*p);
268 esc_value = esc_value * 8 + octtobin (*p);
271 else if (*p && strchr ("\"\\abcfnrtv", *p))
272 print_esc_char (*p++);
273 else if (!posixly_correct && (*p == 'u' || *p == 'U'))
276 unsigned int uni_value;
279 for (esc_length = (esc_char == 'u' ? 4 : 8), ++p;
284 error (EXIT_FAILURE, 0, _("missing hexadecimal number in escape"));
285 uni_value = uni_value * 16 + hextobin (*p);
288 /* A universal character name shall not specify a character short
289 identifier in the range 00000000 through 00000020, 0000007F through
290 0000009F, or 0000D800 through 0000DFFF inclusive. A universal
291 character name shall not designate a character in the required
293 if ((uni_value <= 0x9f
294 && uni_value != 0x24 && uni_value != 0x40 && uni_value != 0x60)
295 || (uni_value >= 0xd800 && uni_value <= 0xdfff))
296 error (EXIT_FAILURE, 0, _("invalid universal character name \\%c%0*x"),
297 esc_char, (esc_char == 'u' ? 4 : 8), uni_value);
299 print_unicode_char (stdout, uni_value, 0);
310 return p - escstart - 1;
313 /* Print string STR, evaluating \ escapes. */
316 print_esc_string (const char *str)
320 str += print_esc (str, true);
325 /* Output a % directive. START is the start of the directive,
326 LENGTH is its length, and ARGUMENT is its argument.
327 If FIELD_WIDTH or PRECISION is UNSPECIFIED, they are args for
328 '*' values in those fields. */
331 print_direc (const char *start, size_t length, int field_width,
332 int precision, const char *argument)
334 char *p; /* Null-terminated copy of % directive. */
336 p = xmalloc ((unsigned) (length + 1));
337 strncpy (p, start, length);
340 switch (p[length - 1])
344 if (field_width == UNSPECIFIED)
346 if (precision == UNSPECIFIED)
347 printf (p, xstrtol (argument));
349 printf (p, precision, xstrtol (argument));
353 if (precision == UNSPECIFIED)
354 printf (p, field_width, xstrtol (argument));
356 printf (p, field_width, precision, xstrtol (argument));
364 if (field_width == UNSPECIFIED)
366 if (precision == UNSPECIFIED)
367 printf (p, xstrtoul (argument));
369 printf (p, precision, xstrtoul (argument));
373 if (precision == UNSPECIFIED)
374 printf (p, field_width, xstrtoul (argument));
376 printf (p, field_width, precision, xstrtoul (argument));
385 if (field_width == UNSPECIFIED)
387 if (precision == UNSPECIFIED)
388 printf (p, xstrtod (argument));
390 printf (p, precision, xstrtod (argument));
394 if (precision == UNSPECIFIED)
395 printf (p, field_width, xstrtod (argument));
397 printf (p, field_width, precision, xstrtod (argument));
402 printf (p, *argument);
406 if (field_width == UNSPECIFIED)
408 if (precision == UNSPECIFIED)
409 printf (p, argument);
411 printf (p, precision, argument);
415 if (precision == UNSPECIFIED)
416 printf (p, field_width, argument);
418 printf (p, field_width, precision, argument);
426 /* Print the text in FORMAT, using ARGV (with ARGC elements) for
427 arguments to any `%' directives.
428 Return the number of elements of ARGV used. */
431 print_formatted (const char *format, int argc, char **argv)
433 int save_argc = argc; /* Preserve original value. */
434 const char *f; /* Pointer into `format'. */
435 const char *direc_start; /* Start of % directive. */
436 size_t direc_length; /* Length of % directive. */
437 int field_width; /* Arg to first '*', or UNSPECIFIED if none. */
438 int precision; /* Arg to second '*', or UNSPECIFIED if none. */
440 for (f = format; *f; ++f)
447 field_width = precision = UNSPECIFIED;
457 print_esc_string (*argv);
463 while (*f == ' ' || *f == '#' || *f == '+' || *f == '-')
474 field_width = xstrtoul (*argv);
475 if (field_width == UNSPECIFIED)
476 error (EXIT_FAILURE, 0, _("invalid field width: %s"),
500 precision = xstrtoul (*argv);
501 if (precision == UNSPECIFIED)
502 error (EXIT_FAILURE, 0, _("invalid precision: %s"),
517 if (*f == 'l' || *f == 'L' || *f == 'h')
522 if (! (*f && strchr ("diouxXfeEgGcs", *f)))
523 error (EXIT_FAILURE, 0, _("%%%c: invalid directive"), *f);
527 print_direc (direc_start, direc_length, field_width,
533 print_direc (direc_start, direc_length, field_width,
538 f += print_esc (f, false);
546 return save_argc - argc;
550 main (int argc, char **argv)
555 initialize_main (&argc, &argv);
556 program_name = argv[0];
557 setlocale (LC_ALL, "");
558 bindtextdomain (PACKAGE, LOCALEDIR);
559 textdomain (PACKAGE);
561 atexit (close_stdout);
565 /* Don't recognize --help or --version if POSIXLY_CORRECT is set. */
566 posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
567 if (!posixly_correct)
568 parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
571 /* The above handles --help and --version.
572 Since there is no other invocation of getopt, handle `--' here. */
573 if (1 < argc && STREQ (argv[1], "--"))
581 fprintf (stderr, _("Usage: %s format [argument...]\n"), program_name);
591 args_used = print_formatted (format, argc, argv);
595 while (args_used > 0 && argc > 0);
599 _("warning: ignoring excess arguments, starting with `%s'"),