How to calculate the length of output that sprintf will generate?

后端 未结 7 1978
谎友^
谎友^ 2021-02-07 01:35

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

7条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 01:44

    You can call int len = snprintf(NULL, 0, "{data:%d}", 12312) to test how much space you need.

    snprintf will print at most size characters, where size is the second argument, and return how many characters would have been necessary to print the whole thing, not counting the terminating '\0'. Because you pass in 0, it won't actually write anything out (and thus will avoid any null pointer exception that would happen by trying to dereference NULL), but it will still return the length that is needed to fit the whole output, which you can use to allocate your buffer.

    At that point you can allocate and print to your buffer, remembering to include one more for the trailing '\0':

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

提交回复
热议问题