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

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

    If you check the performance, you will running snprintf without an output buffer will take roughly the same time as a full invocation.

    So I recommend you to use a smaller buffer just in case, and only call it a second time if the returned size exceeded the buffer size.

    This uses C++'s std::string but I guess you can adapt it for your needs.

    std::string format(const char* format, ...) {
        va_list args;
        va_start(args, format);
        char smallBuffer[1024];
        int size = vsnprintf(smallBuffer, sizeof smallBuffer, format, args);
        va_end(args);
    
        if (size < sizeof smallBuffer) 
            return std::string(smallBuffer);
    
        char buffer[size  + 1]; /* maybe malloc if it's too big */
    
        va_start(args, format);
        vsnprintf(buffer, sizeof buffer, format, args);
        va_end(args);
        return std::string(buffer);
    }
    

    This code will run 2x faster for strings under 1k compared to the longer ones.

提交回复
热议问题