如何确定vswprintf在Linux gcc的缓冲区大小 [英] How to determine buffer size for vswprintf under Linux gcc
问题描述
我需要为格式化函数vswprintf()分配足够的缓冲区。当使用ANSI字符串做同样的事情时,我使用:
vsnprintf(NULL,NULL,pszFormat,args);
这会返回我需要的缓冲区大小。但是似乎这个函数的unicode版本没有这个功能。当我执行:
vswprintf(NULL,NULL,pszFormat,args);
结果值始终为-1。
只有我发现的解决方案是使用大的静态缓冲区来计算所需的大小。但我不喜欢这个解决方案:
static const int nBuffSize = 1024;
static XCHAR evalBuff [nBuffSize];
int nSize = vswprintf(evalBuff,nBuffSize,pszFormat,args);
if(nSize!= -1)
{
return nSize;
}
else
{
throw XXX;
}
有什么办法如何测量unicode字符串所需的缓冲区大小? p>
尊重
Ludek
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++).
这篇关于如何确定vswprintf在Linux gcc的缓冲区大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!