sprintf style function to tell you how big your buffer needs to be?

Started by
7 comments, last by Skute 18 years, 8 months ago
Hi, i need a function which will accept a variable number of arguments and will then tell me how big my buffer needs to be. does anyone know of one?
Mark Ingramhttp://www.mark-ingram.com
Advertisement
That's one of the problems with sprintf. There is no way to determine the size of the buffer, unless you write some very sophisticated function for it.

You could use a stringstream(In case you're using C++). Include the <sstream> header and then do:
stringstream ss;ss << somevar << othervar << somenumber;string s = ss.str(); 


s now contains the end result.

EDIT: In case you're using custom classes to append at the end of the stream, you need to overload the operator << for the class.

Toolmaker

You can use this cheap hack:

char buf[SOME_BIG_NUMBER];
int l=_snprintf(buf,SOME_BIG_NUMBER,your array,your args);
return l;
"C lets you shoot yourself in the foot rather easily. C++ allows you to reuse the bullet!"
In C, you can use snprintf with size = 0.

In C++, just don't.
Quote:Original post by ToohrVyk
In C, you can use snprintf with size = 0.

In C++, just don't.


Wouldn't snprintf return 0?
"C lets you shoot yourself in the foot rather easily. C++ allows you to reuse the bullet!"
Quote:Original post by ToohrVyk
In C, you can use snprintf with size = 0.


Keep in mind that a lot of snprintf() implementations are non C99-compliant, so that even if snprintf is availble on your compiler, it may not work properly (ex: returning -1 instead of the number of bytes written if the buffer is smaller than the size would have been).
Quote:Original post by vNistelrooy
Wouldn't snprintf return 0?


A C99-compliant snprintf() function returns the number of characters that would have been written, not the number of characters actually written.
I use this:

#ifdef __GCC__
#define _vscprintf(format, arglist) vsnprintf(0, 0, format, arglist)
#endif

inline int csprintf(const char* format, ...)
{
va_list argPtr;
va_start(argPtr, format);
int ret = _vscprintf(format, argPtr);
va_end(argPtr);
return ret;
}
2+2=5, for big values of 2!
Yes ive just written a similar function to do that - was just hoping there was a more standard way of doing the same thing!

Thanks :)
Mark Ingramhttp://www.mark-ingram.com

This topic is closed to new replies.

Advertisement