Search code examples
c++gccunicode

How to determine buffer size for vswprintf under Linux gcc


I need to allocate a sufficient buffer for format function vswprintf(). When doing the same thing with ANSI string, I'm using:

vsnprintf( NULL, NULL, pszFormat, args );

which returns me required size of a buffer. But it seems that unicode version of this function doesn't have this functionality. When I execute:

vswprintf( NULL, NULL, pszFormat, args );

result value is always -1.

Only solution which I found is using a large static buffer for calculation required size. But I don't like this solution:

static const int nBuffSize = 1024;
static XCHAR evalBuff[nBuffSize];
int nSize = vswprintf( evalBuff, nBuffSize, pszFormat, args );
if ( nSize != -1 )
{
 return nSize;
}
else
{
 throw XXX;
}

Is there any way how to measure required buffer size for unicode strings?

Regards Ludek


Solution

  • Opening a dummy file to /dev/null (or NUL under windows) and printing to that file to retrieve the size works very well (it is faster than printing to a string):

    #if !defined(_MSC_VER)
       printf_dummy_file = fopen("/dev/null", "wb");
    #else
       printf_dummy_file = fopen("NUL", "wb");
    #endif

    ...

    n = vfprintf(printf_dummy_file, format, args);

    The "fopen" part should be done once (you can use a static variable, or the constructor of a global variable if you are using C++).