How to calculate the length of output that sprintf

2020-05-31 05:08发布

Goal: serialize data to JSON.

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

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 ...

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

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

p.s. i know that i can also get the length of the integer through log but this ways seems nicer.

标签: c printf
7条回答
神经病院院长
2楼-- · 2020-05-31 05:56

Calling snprintf(nullptr, 0, ...) does return the size but it has performance penalty, because it will call IO_str_overflow and which is slow.

If you do care about performance, you can pre-allocate a dummy buffer and pass its pointer and size to ::snprintf. it will be several times faster than the nullptr version.

template<typename ...Args>
size_t get_len(const char* format, Args ...args) {
  static char dummy[4096]; // you can change the default size
  return ::snprintf(dummy, 4096, format, args...) + 1; // +1 for \0
}
查看更多
登录 后发表回答