Home | History | Annotate | Line # | Download | only in printf
printf.c revision 1.4
      1 /*
      2  * Copyright (c) 1989 The Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #ifndef lint
     35 char copyright[] =
     36 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
     37  All rights reserved.\n";
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 /*static char sccsid[] = "from: @(#)printf.c	5.9 (Berkeley) 6/1/90";*/
     42 static char rcsid[] = "$Id: printf.c,v 1.4 1993/11/05 20:12:40 jtc Exp $";
     43 #endif /* not lint */
     44 
     45 #include <ctype.h>
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 #include <limits.h>
     50 #include <locale.h>
     51 #include <err.h>
     52 
     53 void	do_printf();
     54 void	print_escape_str();
     55 int	print_escape();
     56 
     57 int	getchr();
     58 int	getint();
     59 long	getlong();
     60 double	getdouble();
     61 char   *getstr();
     62 
     63 int	rval;
     64 char  **gargv;
     65 
     66 #define isodigit(c)	((c) >= '0' && (c) <= '7')
     67 #define octtobin(c)	((c) - '0')
     68 #define hextobin(c)	((c) >= 'A' && 'c' <= 'F' ? c - 'A' + 10 : (c) >= 'a' && (c) <= 'f' ? c - 'a' + 10 : c - '0')
     69 
     70 #define PF(f, func) { \
     71 	if (fieldwidth) \
     72 		if (precision) \
     73 			(void)printf(f, fieldwidth, precision, func); \
     74 		else \
     75 			(void)printf(f, fieldwidth, func); \
     76 	else if (precision) \
     77 		(void)printf(f, precision, func); \
     78 	else \
     79 		(void)printf(f, func); \
     80 }
     81 
     82 int
     83 main(argc, argv)
     84 	int argc;
     85 	char **argv;
     86 {
     87 	char *format;
     88 
     89 	setlocale (LC_ALL, "");
     90 
     91 	if (argc < 2) {
     92 		fprintf(stderr, "usage: printf format [arg ...]\n");
     93 		exit(1);
     94 	}
     95 
     96 	format = argv[1];
     97 	gargv  = argv + 2;
     98 
     99 	do {
    100 		do_printf(format);
    101 	} while (*gargv);
    102 
    103 	exit (rval);
    104 }
    105 
    106 void
    107 do_printf(format)
    108 	char *format;
    109 {
    110 	static char *skip1, *skip2;
    111 	register char *fmt, *start;
    112 	register int fieldwidth, precision;
    113 	char convch, nextch, *mklong();
    114 
    115 	/*
    116 	 * Basic algorithm is to scan the format string for conversion
    117 	 * specifications -- once one is found, find out if the field
    118 	 * width or precision is a '*'; if it is, gather up value.  Note,
    119 	 * format strings are reused as necessary to use up the provided
    120 	 * arguments, arguments of zero/null string are provided to use
    121 	 * up the format string.
    122 	 */
    123 	skip1 = "#-+ 0";
    124 	skip2 = "*0123456789";
    125 
    126 	/* find next format specification */
    127 	for (fmt = format; *fmt; fmt++) {
    128 		switch (*fmt) {
    129 		case '%':
    130 			start = fmt++;
    131 
    132 			if (*fmt == '%') {
    133 				putchar ('%');
    134 				break;
    135 			} else if (*fmt == 'b') {
    136 				char *p = getstr();
    137 				print_escape_str(p);
    138 				break;
    139 			}
    140 
    141 			/* skip to field width */
    142 			for (; index(skip1, *fmt); ++fmt);
    143 			fieldwidth = *fmt == '*' ? getint() : 0;
    144 
    145 			/* skip to possible '.', get following precision */
    146 			for (; index(skip2, *fmt); ++fmt);
    147 			if (*fmt == '.')
    148 				++fmt;
    149 			precision = *fmt == '*' ? getint() : 0;
    150 
    151 			for (; index(skip2, *fmt); ++fmt);
    152 			if (!*fmt) {
    153 			        warnx ("missing format character");
    154 				rval = 1;
    155 				return;
    156 			}
    157 
    158 			convch = *fmt;
    159 			nextch = *(fmt + 1);
    160 			*(fmt + 1) = '\0';
    161 			switch(convch) {
    162 			case 'c': {
    163 				char p = getchr();
    164 				PF(start, p);
    165 				break;
    166 			}
    167 			case 's': {
    168 				char *p = getstr();
    169 				PF(start, p);
    170 				break;
    171 			}
    172 			case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
    173 				char *f = mklong(start, convch);
    174 				long p = getlong();
    175 				PF(f, p);
    176 				free(f);
    177 				break;
    178 			}
    179 			case 'e': case 'E': case 'f': case 'g': case 'G': {
    180 				double p = getdouble();
    181 				PF(start, p);
    182 				break;
    183 			}
    184 			default:
    185 			        warnx ("%s: invalid directive", start);
    186 			        rval = 1;
    187 			}
    188 			*(fmt + 1) = nextch;
    189 			break;
    190 
    191 		case '\\':
    192 			fmt += print_escape(fmt);
    193 			break;
    194 
    195 		default:
    196 			putchar (*fmt);
    197 			break;
    198 		}
    199 	}
    200 }
    201 
    202 
    203 /*
    204  * Print SysV echo(1) style escape string
    205  */
    206 void
    207 print_escape_str(str)
    208 	register char *str;
    209 {
    210 	int value;
    211 	int c;
    212 
    213 	while (*str) {
    214 		if (*str == '\\') {
    215 			str++;
    216 			/*
    217 			 * %b string octal constants are not like those in C.
    218 			 * They start with a \0, and are followed by 0, 1, 2,
    219 			 * or 3 octal digits.
    220 			 */
    221 			if (*str == '0') {
    222 				str++;
    223 				for (c = 3, value = 0; c-- && isodigit(*str); str++) {
    224 					value <<= 3;
    225 					value += octtobin(*str);
    226 				}
    227 				putchar (value);
    228 				str--;
    229 			} else if (*str == 'c') {
    230 				exit (rval);
    231 			} else {
    232 				str--;
    233 				str += print_escape(str);
    234 			}
    235 		} else {
    236 			putchar (*str);
    237 		}
    238 		str++;
    239 	}
    240 }
    241 
    242 /*
    243  * Print "standard" escape characters
    244  */
    245 int
    246 print_escape(str)
    247 	register char *str;
    248 {
    249 	char *start = str;
    250 	int c;
    251 	int value;
    252 
    253 	str++;
    254 
    255 	switch (*str) {
    256 	case '0': case '1': case '2': case '3':
    257 	case '4': case '5': case '6': case '7':
    258 		for (c = 3, value = 0; c-- && isodigit(*str); str++) {
    259 			value <<= 3;
    260 			value += octtobin(*str);
    261 		}
    262 		putchar(value);
    263 		return str - start - 1;
    264 		/* NOTREACHED */
    265 
    266 	case 'x':
    267 		str++;
    268 		for (value = 0; isxdigit(*str); str++) {
    269 			value <<= 4;
    270 			value += hextobin(*str);
    271 		}
    272 		if (value > UCHAR_MAX) {
    273 			warnx ("escape sequence out of range for character");
    274 			rval = 1;
    275 		}
    276 		putchar (value);
    277 		return str - start - 1;
    278 		/* NOTREACHED */
    279 
    280 	case '\\':			/* backslash */
    281 		putchar('\\');
    282 		break;
    283 
    284 	case '\'':			/* single quote */
    285 		putchar('\'');
    286 		break;
    287 
    288 	case '"':			/* double quote */
    289 		putchar('"');
    290 		break;
    291 
    292 	case 'a':			/* alert */
    293 #ifdef __STDC__
    294 		putchar('\a');
    295 #else
    296 		putchar(007);
    297 #endif
    298 		break;
    299 
    300 	case 'b':			/* backspace */
    301 		putchar('\b');
    302 		break;
    303 
    304 	case 'e':			/* escape */
    305 #ifdef __GNUC__
    306 		putchar('\e');
    307 #else
    308 		putchar(033);
    309 #endif
    310 		break;
    311 
    312 	case 'f':			/* form-feed */
    313 		putchar('\f');
    314 		break;
    315 
    316 	case 'n':			/* newline */
    317 		putchar('\n');
    318 		break;
    319 
    320 	case 'r':			/* carriage-return */
    321 		putchar('\r');
    322 		break;
    323 
    324 	case 't':			/* tab */
    325 		putchar('\t');
    326 		break;
    327 
    328 	case 'v':			/* vertical-tab */
    329 		putchar('\v');
    330 		break;
    331 
    332 	default:
    333 		putchar(*str);
    334 		warnx("unknown escape sequence `\\%c'", *str);
    335 		rval = 1;
    336 	}
    337 
    338 	return 1;
    339 }
    340 
    341 
    342 char *
    343 mklong(str, ch)
    344 	char *str, ch;
    345 {
    346 	int len;
    347 	char *copy;
    348 
    349 	len = strlen(str) + 2;
    350 	if (!(copy = malloc((unsigned int)len))) {
    351 	        err(1, NULL);
    352 		/* NOTREACHED */
    353 	}
    354 	bcopy(str, copy, len - 3);
    355 	copy[len - 3] = 'l';
    356 	copy[len - 2] = ch;
    357 	copy[len - 1] = '\0';
    358 	return(copy);
    359 }
    360 
    361 int
    362 getchr()
    363 {
    364 	if (!*gargv)
    365 		return((int)'\0');
    366 	return((int)**gargv++);
    367 }
    368 
    369 char *
    370 getstr()
    371 {
    372 	if (!*gargv)
    373 		return("");
    374 	return(*gargv++);
    375 }
    376 
    377 static char *number = "+-.0123456789";
    378 int
    379 getint()
    380 {
    381 	if (!*gargv)
    382 		return(0);
    383 
    384 	if (index(number, **gargv))
    385 		return(atoi(*gargv++));
    386 
    387 	return 0;
    388 }
    389 
    390 long
    391 getlong()
    392 {
    393 	long val;
    394 	char *ep;
    395 
    396 	if (!*gargv)
    397 		return(0L);
    398 
    399 	if (**gargv == '\"' || **gargv == '\'') {
    400 		val = gargv[0][1];
    401 		gargv++;
    402 		return val;
    403 	}
    404 
    405 	val = strtol (*gargv, &ep, 0);
    406 	if (*ep) {
    407 		warnx ("incompletely converted argument: %s", *gargv);
    408 		rval = 1;
    409 	}
    410 
    411 	gargv++;
    412 	return val;
    413 }
    414 
    415 double
    416 getdouble()
    417 {
    418 	double val;
    419 	char *ep;
    420 
    421 	if (!*gargv)
    422 		return(0.0);
    423 
    424 	if (**gargv == '\"' || **gargv == '\'') {
    425 		val = gargv[0][1];
    426 		gargv++;
    427 		return val;
    428 	}
    429 
    430 	val = strtod (*gargv, &ep);
    431 	if (*ep) {
    432 		warnx ("incompletely converted argument: %s", *gargv);
    433 		rval = 1;
    434 	}
    435 
    436 	gargv++;
    437 	return val;
    438 }
    439