开发者

MSVC/Linux code for count_sprintf

I need function count_sprintf() that should return

number of characters (not inc nul byte) needed for the formatted buffer, on Win32 and on Linux.

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

There are subtle diffs beteen Win32 vs Linux in return value of vsnprintf when formatted value is longer than buffer size. That's why I ask for help.

Can you give portable code (#ifdef WIN32) for this function.

The function to be used like this:

int bufsize = 1 + count_snprintf(format, ap);  
char *buf = (char*)malloc(bufsize);  
vsnprintf(buf, bufsiz开发者_JAVA百科e, format, ap); // on WIN32, _vsnprint, on Linux, vsnprintf.

Thanks


The VS runtime has the _vscprintf which counts characters needed.

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
}


I can't tell if you want a C solution, C++, or both.

In C++ there's an extremely easy way to solve this problem: Use streams instead of the printf line of functions.

In C I would suggest strongly taking care about any cases where you use a variable format string: They're liable to cause problems if the varargs to the function are even off by a little bit and there's no way for the compiler to help you. If the format is generated externally it's worse as you're basically open to any number of buffer overflow exploits. At least if you have a fixed format string you know how long it will be to start with, and some compilers can do format string checking on the varargs.


On Linux you can use asprintf:

   The  functions asprintf() and vasprintf() are analogs of sprintf(3) and
   vsprintf(3), except that they allocate a string large  enough  to  hold
   the output including the terminating null byte, and return a pointer to
   it via the first argument.  This pointer should be passed to free(3) to
   release the allocated storage when it is no longer needed.


You can use vsnprintf for this -- if you give it a size 0 buffer, it won't actually try to put anything in the buffer, but will still return the number of characters it would have output

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜