T
tonybalinski
I'd like to be able to scan a va_list twice in a v... function, but
can't see how to do it. For example
char *strdupcat(const char *first, ...)
{
char *result, pos;
va_list arg;
size_t len;
const char *next;
va_start(arg, first);
next = first;
while (next) {
len += strlen(next);
next = va_arg(arg, const char *);
}
va_end(arg);
result = pos = malloc(len + 1);
va_start(arg, first);
next = first;
while (next) {
strcpy(pos, next);
pos += strlen(pos);
next = va_arg(arg, const char *);
}
va_end(arg);
*pos = 0;
return result;
}
This should be fine (it's a close paraphrase, but I haven't tried it).
It concatenates string arguments on the argument until one which is
NULL is reached. Now I want to have a function (analogous to vprintf
for printf) that does the same thing called from another variadic
function - how do I handle the rewinding done by va_end/va_start in a
portable way, given that I won't have "first" again? In other words,
how can I write (portably) vstrdupcat in:
char *choseThenConcat(int which, const char *first, ...)
{
char *res;
/* do something with which, then */
va_list args;
va_start(args, first);
res = vstrdupcat(first, args);
va_end();
/* do stuff with res */
return ...something-or-other...
}
can't see how to do it. For example
char *strdupcat(const char *first, ...)
{
char *result, pos;
va_list arg;
size_t len;
const char *next;
va_start(arg, first);
next = first;
while (next) {
len += strlen(next);
next = va_arg(arg, const char *);
}
va_end(arg);
result = pos = malloc(len + 1);
va_start(arg, first);
next = first;
while (next) {
strcpy(pos, next);
pos += strlen(pos);
next = va_arg(arg, const char *);
}
va_end(arg);
*pos = 0;
return result;
}
This should be fine (it's a close paraphrase, but I haven't tried it).
It concatenates string arguments on the argument until one which is
NULL is reached. Now I want to have a function (analogous to vprintf
for printf) that does the same thing called from another variadic
function - how do I handle the rewinding done by va_end/va_start in a
portable way, given that I won't have "first" again? In other words,
how can I write (portably) vstrdupcat in:
char *choseThenConcat(int which, const char *first, ...)
{
char *res;
/* do something with which, then */
va_list args;
va_start(args, first);
res = vstrdupcat(first, args);
va_end();
/* do stuff with res */
return ...something-or-other...
}