sprintf() without trailing null space in C

后端 未结 8 1292
鱼传尺愫
鱼传尺愫 2021-02-01 13:37

Is there a way to use the C sprintf() function without it adding a \'\\0\' character at the end of its output? I need to write formatted text in the middle of a fixed width stri

8条回答
  •  抹茶落季
    2021-02-01 14:12

    Since you're writing to a fixed area, you can do it like this:

    // pointer to fixed area we want to write to
    char* s;
    
    // number of bytes needed, not including the null
    int r = snprintf(0, 0, );
    
    // char following the last char we will write - null goes here
    char c = s[r + 1];
    
    // do the formatted write
    snprintf(s, r + 1, );
    
    // replace what was overwritten
    s[r + 1] = c;
    

提交回复
热议问题