Node:sprintf, Previous:Deprecated formatted string output functions, Up:Deprecated formatted string output functions
sprintf
The sprintf
("string print formatted") command is similar to
asprintf
, except that it is much less safe. Its first parameter
is a string to which to send output. It terminates the string with a
null character. It returns the number of characters stored in the
string, not including the terminating null.
This function will behave unpredictably if the string to which it is
printing overlaps any of its arguments. It is dangerous because the
characters output to the string may overflow it. This problem cannot be
solved with the field width modifier to the conversion specifier,
because only the minimum field width can be specified with it. To avoid
this problem, it is better to use asprintf
, but there is a lot of
C code that still uses sprintf
, so it is important to know about
it. (See asprintf.)
The following code example prints the string Being 4 is cool, but
being free is best of all.
to the string variable my_string
then prints the string on the screen. Notice that my_string
has
been allocated 100 bytes of space, enough to contain the characters
output to it. (See puts, for more information on the puts
function.)
#include <stdio.h> int main() { char my_string[100]; sprintf (my_string, "Being %d is cool, but being free is best of all.", 4); puts (my_string); return 0; }