如何计算 sprintf 将生成的输出长度? [英] How to calculate the length of output that sprintf will generate?

查看:160
本文介绍了如何计算 sprintf 将生成的输出长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:将数据序列化为 JSON.

Goal: serialize data to JSON.

问题:我无法事先知道整数有多少个字符长.

Issue: i cant know beforehand how many chars long the integer is.

我认为一个好方法是使用 sprintf()

i thought a good way to do this is by using sprintf()

size_t length = sprintf(no_buff, "{data:%d}",12312);
char *buff = malloc(length);
snprintf(buff, length, "{data:%d}",12312);
//buff is passed on ...

当然我可以使用像 char a[256] 这样的堆栈变量来代替 no_buff.

Of course i can use a stack variable like char a[256] instead of no_buff.

问题:但是在 C 中是否有像 unix /dev/null 这样的一次性写入的实用程序?像这样:

Question: But is there in C a utility for disposable writes like the unix /dev/null? Smth like this:

#define FORGET_ABOUT_THIS ...
size_t length = sprintf(FORGET_ABOUT_THIS, "{data:%d}",12312);

ps.我知道我也可以通过 log 获取整数的长度,但这种方式似乎更好.

推荐答案

由于 C 是一种简单的语言,因此没有一次性缓冲区"之类的东西——所有的内存管理都在程序员的肩上(有 GNU C 编译器扩展对于这些,但它们不是标准的).

Since C is where simple language, there is no such thing as "disposable buffers" -- all memory management are on programmers shoulders (there is GNU C compiler extensions for these but they are not standard).

无法事先知道整数有多少个字符.

cant know beforehand how many chars long the integer is.

您的问题有更简单的解决方案.snprintf 知道!

There is much easier solution for your problem. snprintf knows!

在兼容 C99 的平台上调用 snprintf 并将 NULL 作为第一个参数:

On C99-compatible platforms call snprintf with NULL as first argument:

ssize_t bufsz = snprintf(NULL, 0, "{data:%d}",12312);
char* buf = malloc(bufsz + 1);
snprintf(buf, bufsz + 1, "{data:%d}",12312);

...

free(buf);

在较旧的 Visual Studio 版本(具有非 C99 兼容的 CRT)中,使用 _scprintf 而不是 snprintf(NULL, ...) 调用.

In older Visual Studio versions (which have non-C99 compatible CRT), use _scprintf instead of snprintf(NULL, ...) call.

这篇关于如何计算 sprintf 将生成的输出长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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