📄 vfprintf.c
字号:
/* * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. *//*FUNCTION<<vfprintf>>, <<vprintf>>, <<vsprintf>>, <<vsnprintf>>, <<vasprintf>>, <<vasnprintf>>---format argument listINDEX vfprintfINDEX vprintfINDEX vsprintfINDEX vsnprintfINDEX vasprintfINDEX vasnprintfANSI_SYNOPSIS #include <stdio.h> #include <stdarg.h> int vprintf(const char *<[fmt]>, va_list <[list]>); int vfprintf(FILE *<[fp]>, const char *<[fmt]>, va_list <[list]>); int vsprintf(char *<[str]>, const char *<[fmt]>, va_list <[list]>); int vsnprintf(char *<[str]>, size_t <[size]>, const char *<[fmt]>, va_list <[list]>); int vasprintf(char **<[strp]>, const char *<[fmt]>, va_list <[list]>); char *vasnprintf(char *<[str]>, size_t *<[size]>, const char *<[fmt]>, va_list <[list]>); int _vprintf_r(struct _reent *<[reent]>, const char *<[fmt]>, va_list <[list]>); int _vfprintf_r(struct _reent *<[reent]>, FILE *<[fp]>, const char *<[fmt]>, va_list <[list]>); int _vsprintf_r(struct _reent *<[reent]>, char *<[str]>, const char *<[fmt]>, va_list <[list]>); int _vasprintf_r(struct _reent *<[reent]>, char **<[str]>, const char *<[fmt]>, va_list <[list]>); int _vsnprintf_r(struct _reent *<[reent]>, char *<[str]>, size_t <[size]>, const char *<[fmt]>, va_list <[list]>); char *_vasnprintf_r(struct _reent *<[reent]>, char *<[str]>, size_t *<[size]>, const char *<[fmt]>, va_list <[list]>);DESCRIPTION<<vprintf>>, <<vfprintf>>, <<vasprintf>>, <<vsprintf>>, <<vsnprintf>>,and <<vasnprintf>> are (respectively) variants of <<printf>>,<<fprintf>>, <<asprintf>>, <<sprintf>>, <<snprintf>>, and<<asnprintf>>. They differ only in allowing their caller to pass thevariable argument list as a <<va_list>> object (initialized by<<va_start>>) rather than directly accepting a variable number ofarguments. The caller is responsible for calling <<va_end>>.<<_vprintf_r>>, <<_vfprintf_r>>, <<_vasprintf_r>>, <<_vsprintf_r>>,<<_vsnprintf_r>>, and <<_vasnprintf_r>> are reentrant versions of theabove.RETURNSThe return values are consistent with the corresponding functions.PORTABILITYANSI C requires <<vprintf>>, <<vfprintf>>, <<vsprintf>>, and<<vsnprintf>>. The remaining functions are newlib extensions.Supporting OS subroutines required: <<close>>, <<fstat>>, <<isatty>>,<<lseek>>, <<read>>, <<sbrk>>, <<write>>.*/#if defined(LIBC_SCCS) && !defined(lint)/*static char *sccsid = "from: @(#)vfprintf.c 5.50 (Berkeley) 12/16/92";*/static char *rcsid = "$Id: vfprintf.c,v 1.43 2002/08/13 02:40:06 fitzsim Exp $";#endif /* LIBC_SCCS and not lint *//* * Actual printf innards. * * This code is large and complicated... */#include <newlib.h>#ifdef INTEGER_ONLY# define VFPRINTF vfiprintf# define _VFPRINTF_R _vfiprintf_r#else# define VFPRINTF vfprintf# define _VFPRINTF_R _vfprintf_r# ifndef NO_FLOATING_POINT# define FLOATING_POINT# endif#endif#define _NO_POS_ARGS#ifdef _WANT_IO_POS_ARGS# undef _NO_POS_ARGS#endif#include <_ansi.h>#include <reent.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <limits.h>#include <stdint.h>#include <wchar.h>#include <sys/lock.h>#include <stdarg.h>#include "local.h"#include "fvwrite.h"#include "vfieeefp.h"/* Currently a test is made to see if long double processing is warranted. This could be changed in the future should the _ldtoa_r code be preferred over _dtoa_r. */#define _NO_LONGDBL#if defined _WANT_IO_LONG_DOUBLE && (LDBL_MANT_DIG > DBL_MANT_DIG)#undef _NO_LONGDBL#endif#define _NO_LONGLONG#if defined _WANT_IO_LONG_LONG \ && (defined __GNUC__ || __STDC_VERSION__ >= 199901L)# undef _NO_LONGLONG#endif/* * Flush out all the vectors defined by the given uio, * then reset it so that it can be reused. */static int_DEFUN(__sprint_r, (ptr, fp, uio), struct _reent *ptr _AND FILE *fp _AND register struct __suio *uio){ register int err; if (uio->uio_resid == 0) { uio->uio_iovcnt = 0; return (0); } err = __sfvwrite_r(ptr, fp, uio); uio->uio_resid = 0; uio->uio_iovcnt = 0; return (err);}/* * Helper function for `fprintf to unbuffered unix file': creates a * temporary buffer. We only work on write-only files; this avoids * worries about ungetc buffers and so forth. */static int_DEFUN(__sbprintf, (rptr, fp, fmt, ap), struct _reent *rptr _AND register FILE *fp _AND _CONST char *fmt _AND va_list ap){ int ret; FILE fake; unsigned char buf[BUFSIZ]; /* copy the important variables */ fake._flags = fp->_flags & ~__SNBF; fake._file = fp->_file; fake._cookie = fp->_cookie; fake._write = fp->_write; /* set up the buffer */ fake._bf._base = fake._p = buf; fake._bf._size = fake._w = sizeof (buf); fake._lbfsize = 0; /* not actually used, but Just In Case */#ifndef __SINGLE_THREAD__ __lock_init_recursive (fake._lock);#endif /* do the work, then copy any error status */ ret = _VFPRINTF_R (rptr, &fake, fmt, ap); if (ret >= 0 && _fflush_r (rptr, &fake)) ret = EOF; if (fake._flags & __SERR) fp->_flags |= __SERR;#ifndef __SINGLE_THREAD__ __lock_close_recursive (fake._lock);#endif return (ret);}#ifdef FLOATING_POINT# include <locale.h># include <math.h>/* For %La, an exponent of 15 bits occupies the exponent character, a sign, and up to 5 digits. */# define MAXEXPLEN 7# define DEFPREC 6# ifdef _NO_LONGDBLextern char *_dtoa_r _PARAMS((struct _reent *, double, int, int, int *, int *, char **));# define _PRINTF_FLOAT_TYPE double# define _DTOA_R _dtoa_r# define FREXP frexp# else /* !_NO_LONGDBL */extern char *_ldtoa_r _PARAMS((struct _reent *, _LONG_DOUBLE, int, int, int *, int *, char **));extern int _EXFUN(_ldcheck,(_LONG_DOUBLE *));# define _PRINTF_FLOAT_TYPE _LONG_DOUBLE# define _DTOA_R _ldtoa_r/* FIXME - frexpl is not yet supported; and cvt infloops if (double)f converts a finite value into infinity. *//* # define FREXP frexpl */# define FREXP(f,e) ((_LONG_DOUBLE) frexp ((double)f, e))# endif /* !_NO_LONGDBL */static char *cvt(struct _reent *, _PRINTF_FLOAT_TYPE, int, int, char *, int *, int, int *, char *);static int exponent(char *, int, int);#endif /* FLOATING_POINT *//* BUF must be big enough for the maximum %#llo (assuming long long is at most 64 bits, this would be 23 characters), the maximum multibyte character %C, and the maximum default precision of %La (assuming long double is at most 128 bits with 113 bits of mantissa, this would be 29 characters). %e, %f, and %g use reentrant storage shared with mprec. All other formats that use buf get by with fewer characters. Making BUF slightly bigger reduces the need for malloc in %.*a and %S, when large precision or long strings are processed. */#define BUF 40#if defined _MB_CAPABLE && MB_LEN_MAX > BUF# undef BUF# define BUF MB_LEN_MAX#endif#ifndef _NO_LONGLONG# define quad_t long long# define u_quad_t unsigned long long#else# define quad_t long# define u_quad_t unsigned long#endiftypedef quad_t * quad_ptr_t;typedef _PTR void_ptr_t;typedef char * char_ptr_t;typedef long * long_ptr_t;typedef int * int_ptr_t;typedef short * short_ptr_t;#ifndef _NO_POS_ARGS# ifdef NL_ARGMAX# define MAX_POS_ARGS NL_ARGMAX# else# define MAX_POS_ARGS 32# endifunion arg_val{ int val_int; u_int val_u_int; long val_long; u_long val_u_long; float val_float; double val_double; _LONG_DOUBLE val__LONG_DOUBLE; int_ptr_t val_int_ptr_t; short_ptr_t val_short_ptr_t; long_ptr_t val_long_ptr_t; char_ptr_t val_char_ptr_t; quad_ptr_t val_quad_ptr_t; void_ptr_t val_void_ptr_t; quad_t val_quad_t; u_quad_t val_u_quad_t; wint_t val_wint_t;};static union arg_val *_EXFUN(get_arg, (struct _reent *data, int n, char *fmt, va_list *ap, int *numargs, union arg_val *args, int *arg_type, char **last_fmt));#endif /* !_NO_POS_ARGS *//* * Macros for converting digits to letters and vice versa */#define to_digit(c) ((c) - '0')#define is_digit(c) ((unsigned)to_digit (c) <= 9)#define to_char(n) ((n) + '0')/* * Flags used during conversion. */#define ALT 0x001 /* alternate form */#define HEXPREFIX 0x002 /* add 0x or 0X prefix */#define LADJUST 0x004 /* left adjustment */#define LONGDBL 0x008 /* long double */#define LONGINT 0x010 /* long integer */#ifndef _NO_LONGLONG# define QUADINT 0x020 /* quad integer */#else /* ifdef _NO_LONGLONG, make QUADINT equivalent to LONGINT, so that %lld behaves the same as %ld, not as %d, as expected if: sizeof (long long) = sizeof long > sizeof int */# define QUADINT LONGINT#endif#define SHORTINT 0x040 /* short integer */#define ZEROPAD 0x080 /* zero (as opposed to blank) pad */#define FPT 0x100 /* Floating point number */#ifdef _WANT_IO_C99_FORMATS# define CHARINT 0x200 /* char as integer */#else /* define as 0, to make SARG and UARG occupy fewer instructions */# define CHARINT 0#endifint _EXFUN(_VFPRINTF_R, (struct _reent *, FILE *, _CONST char *, va_list));int _DEFUN(VFPRINTF, (fp, fmt0, ap), FILE * fp _AND _CONST char *fmt0 _AND va_list ap){ int result; result = _VFPRINTF_R (_REENT, fp, fmt0, ap); return result;}int _DEFUN(_VFPRINTF_R, (data, fp, fmt0, ap), struct _reent *data _AND FILE * fp _AND _CONST char *fmt0 _AND va_list ap){ register char *fmt; /* format string */ register int ch; /* character from fmt */ register int n, m; /* handy integers (short term usage) */ register char *cp; /* handy char pointer (short term usage) */ register struct __siov *iovp;/* for PRINT macro */ register int flags; /* flags as above */ char *fmt_anchor; /* current format spec being processed */#ifndef _NO_POS_ARGS int N; /* arg number */ int arg_index; /* index into args processed directly */ int numargs; /* number of varargs read */ char *saved_fmt; /* saved fmt pointer */ union arg_val args[MAX_POS_ARGS]; int arg_type[MAX_POS_ARGS]; int is_pos_arg; /* is current format positional? */ int old_is_pos_arg; /* is current format positional? */#endif int ret; /* return value accumulator */ int width; /* width from format (%8d), or 0 */ int prec; /* precision from format (%.3d), or -1 */ char sign; /* sign prefix (' ', '+', '-', or \0) */#ifdef FLOATING_POINT char *decimal_point = _localeconv_r (data)->decimal_point; char softsign; /* temporary negative sign for floats */ union { int i; _PRINTF_FLOAT_TYPE fp; } _double_ = {0};# define _fpvalue (_double_.fp) int expt; /* integer value of exponent */ int expsize = 0; /* character count for expstr */ int ndig = 0; /* actual number of digits returned by cvt */ char expstr[MAXEXPLEN]; /* buffer for exponent string */#endif /* FLOATING_POINT */ u_quad_t _uquad; /* integer arguments %[diouxX] */ enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */ int dprec; /* a copy of prec if [diouxX], 0 otherwise */ int realsz; /* field size expanded by dprec */ int size; /* size of converted field or string */ char *xdigs = NULL; /* digits for [xX] conversion */#define NIOV 8 struct __suio uio; /* output information: summary */ struct __siov iov[NIOV];/* ... and individual io vectors */ char buf[BUF]; /* space for %c, %S, %[diouxX], %[aA] */ char ox[2]; /* space for 0x hex-prefix */#ifdef _MB_CAPABLE wchar_t wc; mbstate_t state; /* mbtowc calls from library must not change state */#endif char *malloc_buf = NULL;/* handy pointer for malloced buffers */ /* * Choose PADSIZE to trade efficiency vs. size. If larger printf * fields occur frequently, increase PADSIZE and make the initialisers * below longer. */#define PADSIZE 16 /* pad chunk size */ static _CONST char blanks[PADSIZE] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; static _CONST char zeroes[PADSIZE] = {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};#ifdef _MB_CAPABLE memset (&state, '\0', sizeof (state));#endif /* * BEWARE, these `goto error' on error, and PAD uses `n'. */#define PRINT(ptr, len) { \ iovp->iov_base = (ptr); \ iovp->iov_len = (len); \ uio.uio_resid += (len); \ iovp++; \ if (++uio.uio_iovcnt >= NIOV) { \ if (__sprint_r(data, fp, &uio)) \ goto error; \ iovp = iov; \ } \}#define PAD(howmany, with) { \ if ((n = (howmany)) > 0) { \ while (n > PADSIZE) { \ PRINT (with, PADSIZE); \ n -= PADSIZE; \ } \ PRINT (with, n); \ } \}#define FLUSH() { \ if (uio.uio_resid && __sprint_r(data, fp, &uio)) \ goto error; \ uio.uio_iovcnt = 0; \ iovp = iov; \} /* Macros to support positional arguments */#ifndef _NO_POS_ARGS# define GET_ARG(n, ap, type) \ (is_pos_arg \ ? (n < numargs \ ? args[n].val_##type \ : get_arg (data, n, fmt_anchor, &ap, &numargs, args, \ arg_type, &saved_fmt)->val_##type) \ : (arg_index++ < numargs \ ? args[n].val_##type \ : (numargs < MAX_POS_ARGS \
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -