1 /* @(#)jsdprintf.c 1.2 17/08/03 Copyright 1985, 1989, 1995-2017 J. Schilling */
2 /*
3 * Copyright (c) 1985, 1989, 1995-2017 J. Schilling
4 */
5 /*
6 * The contents of this file are subject to the terms of the
7 * Common Development and Distribution License, Version 1.0 only
8 * (the "License"). You may not use this file except in compliance
9 * with the License.
10 *
11 * See the file CDDL.Schily.txt in this distribution for details.
12 * A copy of the CDDL is also available via the Internet at
13 * http://www.opensource.org/licenses/cddl1.txt
14 *
15 * When distributing Covered Code, include this CDDL HEADER in each
16 * file and include the License file CDDL.Schily.txt from this distribution.
17 */
18
19 #include <schily/mconfig.h>
20 #include <schily/stdio.h>
21 #include <schily/varargs.h>
22 #include <schily/standard.h>
23 #include <schily/schily.h>
24
25 #define BFSIZ 256
26
27 typedef struct {
28 short cnt;
29 char *ptr;
30 char buf[BFSIZ];
31 int count;
32 int fd;
33 } *BUF, _BUF;
34
35 LOCAL void _bflush __PR((BUF));
36 LOCAL void _bput __PR((char, void *));
37 EXPORT int js_dprintf __PR((int, const char *, ...)) __printflike__(2, 3);
38
39 LOCAL void
_bflush(bp)40 _bflush(bp)
41 register BUF bp;
42 {
43 bp->count += bp->ptr - bp->buf;
44 if (write(bp->fd, bp->buf, bp->ptr - bp->buf) < 0)
45 bp->count = EOF;
46 bp->ptr = bp->buf;
47 bp->cnt = BFSIZ;
48 }
49
50 #ifdef PROTOTYPES
51 LOCAL void
_bput(char c,void * l)52 _bput(char c, void *l)
53 #else
54 LOCAL void
55 _bput(c, l)
56 char c;
57 void *l;
58 #endif
59 {
60 register BUF bp = (BUF)l;
61
62 *bp->ptr++ = c;
63 if (--bp->cnt <= 0)
64 _bflush(bp);
65 }
66
67 /* VARARGS2 */
68 #ifdef PROTOTYPES
69 EXPORT int
js_dprintf(int fd,const char * form,...)70 js_dprintf(int fd, const char *form, ...)
71 #else
72 EXPORT int
73 js_dprintf(fd, form, va_alist)
74 int fd;
75 char *form;
76 va_dcl
77 #endif
78 {
79 va_list args;
80 _BUF bb;
81
82 bb.ptr = bb.buf;
83 bb.cnt = BFSIZ;
84 bb.count = 0;
85 bb.fd = fd;
86 #ifdef PROTOTYPES
87 va_start(args, form);
88 #else
89 va_start(args);
90 #endif
91 format(_bput, &bb, form, args);
92 va_end(args);
93 if (bb.cnt < BFSIZ)
94 _bflush(&bb);
95 return (bb.count);
96 }
97