c++ - count_sprintf 的 MSVC/Linux 代码

标签 c++ c visual-c++ stdio

我需要应该返回的函数 count_sprintf()
格式化缓冲区所需的字符数(不包括 nul 字节),在 Win32 和 Linux 上。

int count_sprintf(const char *format, va_list ap);

当格​​式化值长于缓冲区大小时,在 vsnprintf 的返回值中,Win32 与 Linux 之间存在细微差别。这就是我寻求帮助的原因。

你能为这个功能提供可移植代码(#ifdef WIN32)吗?

要这样使用的函数:

int bufsize = 1 + count_snprintf(format, ap);  
char *buf = (char*)malloc(bufsize);  
vsnprintf(buf, bufsize, format, ap); // on WIN32, _vsnprint, on Linux, vsnprintf.

谢谢

最佳答案

VS 运行时有 _vscprintf 来计算所需的字符数。

int count_sprintf(const char *format, va_list ap) {
#ifdef WIN32
  return _vscprintf(format, ap);
#else
  char c;
  return vsnprintf(&c, 1, format, ap);
#endif
}

关于c++ - count_sprintf 的 MSVC/Linux 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5184459/

相关文章:

c++ - 标准化之前多长时间 `string` 可用?

c - 为什么矢量化循环没有性能提升

c - 太多参数无法运行 'int mkdir(const char*)'

c - 我们如何在 C 的作用域之外访问 auto 和 static 变量?

c++ - Link Error : xxx is already defined in *****.LIB::究竟是什么错误?

c++ - 我无法使用 VS2010 运行 openCV2.3.1,因为找不到 opencv_core231d.dll

c++ - tm_wday 返回 0-6 范围之外的大整数

c++ - 视觉C++ : Exporting decorated function name in a def file

c++ - C++ 中的空构造函数

visual-studio-2010 - 在 Visual Studio 2010 中 Clean/Build 成功时重建失败