有什么方法可以确定sprintf将写入多少个字符? [英] Is there any way to determine how many characters will be written by sprintf?

查看:170
本文介绍了有什么方法可以确定sprintf将写入多少个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++。

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

I want to write a potentially very long formatted string using sprintf (specifically a secure counted version like _snprintf_s, but the idea is the same). The approximate length is unknown at compile time so I'll have to use some dynamically allocated memory rather than relying on a big static buffer. Is there any way to determine how many characters will be needed for a particular sprintf call so I can always be sure I've got a big enough buffer?

我的后备是我只是将格式字符串的长度加倍,然后尝试一下。如果可以,很好,如果不能,我将缓冲区的大小加倍,然后重试。重复直到合适为止。

My fallback is I'll just take the length of the format string, double it, and try that. If it works, great, if it doesn't I'll just double the size of the buffer and try again. Repeat until it fits. Not exactly the cleverest solution.

看起来C99支持将NULL传递给snprintf以获取长度。我想我可以创建一个模块来包装该功能(如果没有其他功能的话),但是我对此想法并不疯狂。

It looks like C99 supports passing NULL to snprintf to get the length. I suppose I could create a module to wrap that functionality if nothing else, but I'm not crazy about that idea.

也许是fprintf到 / dev / null / nul可能可以代替?还有其他想法吗?

Maybe an fprintf to "/dev/null"/"nul" might work instead? Any other ideas?

编辑:或者,有没有办法压缩 sprintf,使它达到中间写入速度?如果可能的话,可以填充缓冲区,对其进行处理,然后从中断处开始重新填充。

Alternatively, is there any way to "chunk" the sprintf so it picks up mid-write? If that's possible it could fill the buffer, process it, then start refilling from where it left off.

推荐答案

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.

这意味着您可以调用大小为0的 snprintf 。什么都不会写,返回值将告诉您需要分配多少空间给字符串:

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, ...);

这篇关于有什么方法可以确定sprintf将写入多少个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆