Using printf type variable parameters in your function

The C programming languagI needed this in a bit of debug code. I wanted it to work like printf where there’s a format string containing one or more % format specifications and then write this into a buffer and dump it where ever.

C has a library stdarg which lets you do this. It’s not the most intuitive but it’s definitely worth understanding.

What I’m wanting to do is a function that does something like this (assume s1,s2 and s3 are char *).

sprintf(buffer,"Some string values %s %s %s",s1,s2,s3);
doSomething(buffer);

But in my own function and with the ability to have 0,1,2 or how ever many parameters without having to write a separate function for each. Kind of what printf does.

Here’s the code:

 

#include <stdarg.h>
void op(char* s, ...) {
	char buffer[50];
	va_list argptr;
	va_start(argptr, s);
	vsprintf_s(buffer,sizeof(buffer),s,argptr);
	OutputDebugStringA(buffer);
	va_end(argptr);
}

The … represent the variable number of parameters. it’s called the variadic operator. To access the actual parameters needs the various va_ macros and types. For instance va_list is a type that manages the list of parameters. The va_start macro takes the list and the parameter before the list. vsprintf_s is the Microsoft secure version of vsprintf. Both are the variable parameter equivalent of sprintf/sprintf_s.

OutputDebugString is the Windows debug string function. Finally the va_end tidies up everything.

So you use this just like printf, except the output goes to the Debug channel and can be picked up in Visual Studio (if debugging) or by running the SysInternals free DebugView utility.

Note, the original version of this used OutputDebugString but I found it was outputting gibberish. I correctly guessed that it was linking to OutputDebugStringW ; the MBCS version and changing it to OutputDebugStringA (the ASCII version) fixed it. Something to watch out for on Windows. 

(Visited 119 times, 1 visits today)