更新时间:2023-11-13 09:49:04
dev / null(或Windows下的NUL)并打印到该文件以检索大小的效果非常好(它比打印到字符串更快):
#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);
fopen部分应该做一次(你可以使用静态变量,或者使用C ++的全局变量的构造函数)。
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
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++).