11 static char _ibuf
[BUFSZ
], _obuf
[BUFSZ
], _ebuf
[BUFSZ
];
12 static FILE _stdin
= {0, EOF
, _ibuf
, NULL
, BUFSZ
, 0};
13 static FILE _stdout
= {1, EOF
, NULL
, _obuf
, 0, BUFSZ
};
14 static FILE _stderr
= {2, EOF
, NULL
, _ebuf
, 0, 1};
15 FILE *stdin
= &_stdin
;
16 FILE *stdout
= &_stdout
;
17 FILE *stderr
= &_stderr
;
19 FILE *fopen(char *path
, char *mode
)
24 if (strchr(mode
, '+'))
27 flags
= *mode
== 'r' ? O_RDONLY
: O_WRONLY
;
35 fp
= malloc(sizeof(*fp
));
36 memset(fp
, 0, sizeof(*fp
));
37 fp
->fd
= open(path
, flags
, 0600);
43 fp
->ibuf
= malloc(BUFSZ
);
44 fp
->obuf
= malloc(BUFSZ
);
54 int ret
= close(fp
->fd
);
67 if (write(fp
->fd
, fp
->obuf
, fp
->olen
) != fp
->olen
)
73 static int oc(FILE *fp
, int c
)
75 if (fp
->olen
< fp
->osize
) {
76 fp
->obuf
[fp
->olen
++] = c
;
79 if (c
== '\n' || fp
->olen
== fp
->osize
)
84 static void ostr(FILE *fp
, char *s
, int wid
)
86 int fill
= wid
- strlen(s
);
93 static int digits(unsigned long n
, int base
)
101 static char *digs
= "0123456789abcdef";
103 static void oint(FILE *fp
, unsigned long n
, int base
, int sign
, int wid
, int fill
)
110 if (sign
&& (signed long) n
< 0) {
115 for (i
= 0; i
< d
; i
++) {
116 s
[d
- i
- 1] = digs
[n
% base
];
120 for (i
= d
+ neg
; i
< wid
; i
++)
127 int vfprintf(FILE *fp
, char *fmt
, va_list ap
)
145 while (isdigit(*s
)) {
149 switch ((c
= *s
++)) {
151 oint(fp
, va_arg(ap
, long), 10, 1, wid
, fill
);
154 oint(fp
, va_arg(ap
, long), 10, 0, wid
, fill
);
158 oint(fp
, va_arg(ap
, long), 16, 0, wid
, fill
);
161 oc(fp
, va_arg(ap
, int));
164 ostr(fp
, va_arg(ap
, char *), wid
);
173 return fp
->ostat
- beg
;
181 fprintf(stderr
, "%s: %s\n", s
, sys_errlist
[idx
]);
184 int vsnprintf(char *dst
, int sz
, char *fmt
, va_list ap
)
190 ret
= vfprintf(&f
, fmt
, ap
);
195 int vsprintf(char *dst
, char *fmt
, va_list ap
)
197 return vsnprintf(dst
, 1 << 20, fmt
, ap
);
200 int printf(char *fmt
, ...)
205 ret
= vfprintf(stdout
, fmt
, ap
);
210 int fprintf(FILE *fp
, char *fmt
, ...)
215 ret
= vfprintf(fp
, fmt
, ap
);
220 int sprintf(char *dst
, char *fmt
, ...)
225 ret
= vsprintf(dst
, fmt
, ap
);
230 int snprintf(char *dst
, int sz
, char *fmt
, ...)
235 ret
= vsnprintf(dst
, sz
, fmt
, ap
);