Originally posted by Xzyx987X
I was wondering how exactly this is done. printf is usually one of the first functions you learn how to use, but no one really explains how it manages to allow you to plug in an endless amount of parameters. What I have in mind is a function that would allow you to merge a list of strings all into one, but I don't even know where to start...
Also, keep in mind that variable-argument functions must have some means for detecting the end-of-data condition. Functions like printf() do that by simply counting the args in the format string 'by hand'. Another typical approach is to have the user pass some sentinel value (usually zero) to signal the end of data. Here's an example:
Code:
char * bigstrcat(char * buffer, const char * first, ...)
{
const char * next = first;
va_list lst;
va_start(lst, first);
while(next != NULL)
{
strcat(buffer, next);
next = va_arg(lst, char*);
}
va_end(lst);
return buffer;
}
Which would be used like this:
Code:
int main()
{
char str[1024] = "Testing";
bigstrcat(str, "...one", "...two", "...three.", NULL);
printf("%s\n", str);
return 0;
}
Another handy function is vsprintf(), which can be very useful for rolling custom made functions:
Code:
int log(FILE * out, int code, const char * message, ...)
{
const char
* success = "SUCCESS",
* warning = "WARNING",
* fatal = "FATAL",
* type = code ? code < 0 ? fatal : warning : success;
time_t now = time(NULL);
char entry[(strlen(message) * 2) + 1024];
va_list lst;
va_start(lst, message);
vsprintf(entry, message, lst);
va_end(lst);
fprintf(out, "%s Code [%d] (%s) '%s'.\n",
asctime(localtime(&now)), code, type, entry);
if(code < 0)
{
fclose(out);
exit(code);
}
return code;
}
int main()
{
log(stdout, 0, "Processed");
log(stdout, 4, "Too many parameters");
log(stdout, -6, "Internal exception");
return 0;
}