1 |
/* strnf.c -- like sprintf, but with a buffer size argument */ |
2 |
|
3 |
/* Copyright 1992 Mark Russell, University of Kent at Canterbury. |
4 |
* |
5 |
* You can do what you like with this source code as long as |
6 |
* you don't try to make money out of it and you include an |
7 |
* unaltered copy of this message (including the copyright). |
8 |
*/ |
9 |
|
10 |
char ukcprog_strnf_sccsid[] = "$Id: strnf.c,v 1.7 1993/10/25 11:40:55 mtr Exp $ UKC"; |
11 |
|
12 |
#ifdef __STDC__ |
13 |
#include <stdarg.h> |
14 |
#else |
15 |
#include <varargs.h> |
16 |
#endif |
17 |
|
18 |
#include <stdio.h> |
19 |
#include <stdlib.h> |
20 |
#include <string.h> |
21 |
#ifndef __STDC__ |
22 |
#include <memory.h> |
23 |
#endif |
24 |
|
25 |
#include "ukcprog.h" |
26 |
|
27 |
|
28 |
#ifdef __STDC__ |
29 |
void |
30 |
strnf(char *buf, size_t bufsize, const char *fmt, ...) |
31 |
{ |
32 |
|
33 |
#else /* !__STDC__ */ |
34 |
void |
35 |
strnf(va_alist) |
36 |
va_dcl |
37 |
{ |
38 |
char *buf; |
39 |
int bufsize; |
40 |
char *fmt; |
41 |
#endif /* !__STDC__ */ |
42 |
va_list args; |
43 |
char *s; |
44 |
|
45 |
#ifdef __STDC__ |
46 |
va_start(args, fmt); |
47 |
#else |
48 |
va_start(args); |
49 |
buf = va_arg(args, char *); |
50 |
bufsize = va_arg(args, size_t); |
51 |
fmt = va_arg(args, char *); |
52 |
#endif |
53 |
|
54 |
s = formf(buf, (int)bufsize, fmt, args); |
55 |
|
56 |
va_end(args); |
57 |
|
58 |
/* If formf had to allocate a buffer then the supplied buf |
59 |
* was too small. Copy what will fit and free the formf buffer. |
60 |
*/ |
61 |
if (s != buf) { |
62 |
memcpy(buf, s, (size_t)(bufsize - 1)); |
63 |
buf[bufsize - 1] = '\0'; |
64 |
free(s); |
65 |
} |
66 |
} |