c++ - 有什么方法可以确定 sprintf 将写入多少个字符?

标签 c++ string printf

我正在使用 C++。

我想使用 sprintf 编写一个可能很长的格式化字符串(特别是像 _snprintf_s 这样的安全计数版本,但想法是一样的)。近似长度在编译时是未知的,所以我将不得不使用一些动态分配的内存,而不是依赖一个大的静态缓冲区。有什么方法可以确定特定 sprintf 调用需要多少个字符,这样我就可以始终确定我有足够大的缓冲区?

我的后备方案是我将获取格式字符串的长度,将其加倍,然后尝试。如果有效,那就太好了,如果无效,我将缓冲区的大小加倍,然后再试一次。重复直到合适。不完全是最聪明的解决方案。

看起来 C99 支持将 NULL 传递给 snprintf 以获取长度。如果不出意外,我想我可以创建一个模块来包装该功能,但我并不热衷于这个想法。

也许 fprintf 到 "/dev/null"/"nul"可能会起作用?还有其他想法吗?

编辑:或者,有没有办法“分 block ” sprintf 以便它在写入过程中拾取?如果可能的话,它可以填充缓冲区,处理它,然后从停止的地方开始重新填充。

最佳答案

snprintf 的手册页说:

   Return value
       Upon  successful  return,  these  functions return the number of
       characters printed (not including the trailing '\0' used to  end
       output to strings).  The functions snprintf and vsnprintf do not
       write more than size bytes (including the  trailing  '\0').   If
       the output was truncated due to this limit then the return value
       is the number of characters (not including  the  trailing  '\0')
       which  would  have  been  written  to the final string if enough
       space had been available. Thus, a return value of size  or  more
       means  that  the  output  was  truncated.  (See also below under
       NOTES.)  If an output error is encountered, a negative value  is
       returned.

What this means is that you can call snprintf with a size of 0. Nothing will get written, and the return value will tell you how much space you need to allocate to your string:

int how_much_space = snprintf(NULL, 0, fmt_string, param0, param1, ...);

关于c++ - 有什么方法可以确定 sprintf 将写入多少个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/514870/

相关文章:

JavaFX - 获取当前在 TextArea 中输入的单词

java - Java中使用 ".printf(...)"打印内存中的值

c - 如何在 C 语言中逐个字符地打印字符串?

C printf 无符号字符数组

c++ - Windows 应用程序音量混合器

c++ - 我可以在 C++11 的类外执行继承吗?

java - 我如何用IP和端口来划分字符串?

c - 在循环中使用 strlen 反转 C 中的字符串

c++ - 使用 front_inserter 而不是 back_inserter

c++ - 是否允许注释与预处理器指令在同一行,在这种情况下它们的含义是什么?