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

后端 未结 7 1977
谎友^
谎友^ 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:50

    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.

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

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

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

提交回复
热议问题