读好书,交益友
分类: C/C++
2013-10-16 17:58:54
以前使用snprintf()不是一年两年了,以前经常写
snprintf(params->ipsubnet,IP_MASK,"%s/%d",g_sslvpnconfig.serverip,slash);
params->ipsubnet[IP_MASK-1]='\0';
最近在做nginx模块时发现了问题,snprintf格式化字符串时,自动少了一位。
man了一下,The functions snprintf() and vsnprintf() write at most size bytes (including the trailing null byte ('\0')) to str.
我记得vs2005,不会自动添加'\0'
#include
#include
int main (void)
{
char buffer[2];
snprintf(buffer, sizeof(buffer), "SomeString");
return 0;
}
vs2010没有snprintf函数,提供了_snprintf,因为snprintf是c99的一部分,微软没有支持c99,转而支持c++11,snprintf是c++11的一部分。
#ifdef _MSC_VER
#define snprintf c99_snprintf
inline int c99_snprintf(char* str, size_t size, const char* format, ...)
{
int count;
va_list ap;
va_start(ap, format);
count = c99_vsnprintf(str, size, format, ap);
va_end(ap);
return count;
}
inline int c99_vsnprintf(char* str, size_t size, const char* format, va_list ap)
{
int count = -1;
if (size != 0)
count = _vsnprintf_s(str, size, _TRUNCATE, format, ap);
if (count == -1)
count = _vscprintf(format, ap);
return count;
}
#endif // _MSC_VER