writing formatted data of unknown length to a string (C programming)

后端 未结 5 1026
Happy的楠姐
Happy的楠姐 2020-12-31 11:36

The following C function:

int sprintf ( char * str, const char * format, ... );

writes formatted data to a string. The size of the array pa

5条回答
  •  礼貌的吻别
    2020-12-31 11:47

    Using snprintf

    Most people will tell you to use snprintf() because it won't overrun the end of your buffer.

    And this is OK advice. The usual "design pattern" is to declare a temporary fixed-size buffer that is larger than the string is ever likely to be and snprintf() to that. If the string needs to be saved for a while you can then measure its length, malloc(3) another, and strcpy(3) the temporary buffer to the semi-permanent malloc() buffer.


    A two-pass approach

    There is another way.

    C99 specifies that if the buffer is NULL then no bytes are written but the actual length that would have been written is returned. This allows you to do a dummy first pass, malloc() a buffer, and then snprintf() to that buffer. (In theory you could use plain sprintf(), as the length is now known, but I wouldn't.)

    Anyway, I'm not sure I would count on all this if my program had to run on every OS ever made in the past, but it's a reasonable pattern for most people to use these days.

提交回复
热议问题