sprintf() without trailing null space in C

后端 未结 8 1317
鱼传尺愫
鱼传尺愫 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 13:58

    Here's an option for memory constrained devices. It trades off speed for using less RAM. I sometimes have to do this to update the middle of a string that gets printed to a LCD.

    The idea is that you first call snprintf with a zero sized buffer to determine which index will get clobbered by the null terminator.

    You can run the below code here: https://rextester.com/AMOOC49082

    #include 
    #include 
    
    int main(void)
    {
      char buf[100] = { 'a', 'b', 'c', 'd', 'e' };
      const size_t buf_size = sizeof(buf);
      const int i = 123;
    
      int result = snprintf(buf, 0, "%i", i);
      if (result < 0)
      {
        printf("snprintf error: %i\n", result);
        return -1;
      }
    
      int clobbered_index = result; //this index will get the null term written into it
    
      if (result >= buf_size)
      {
        printf("buffer not large enough. required %i chars\n", result + 1);
        return -1;
      }
    
      char temp_char = buf[clobbered_index];
      result = snprintf(buf, buf_size, "%i", i); //add result error checking here to catch future mistakes
      buf[clobbered_index] = temp_char;
    
      printf("buf:%s\n", buf);
    
      return 0;
    }
    

    Prints buf:123de

提交回复
热议问题