snprintf()

Formats a character string array.

  #include <stdio.h>
  
  int snprintf(char * s, size_t n, const char * format, ...);    
Parameter

s

A pointer to the character string from which to store the formatted text.

n

Maximum number of characters to store in s.

format

A pointer to a format string.

Remarks

The snprintf() function works identically to fprintf() except that the output is written into the array s instead of to a stream. If n is zero nothing is written; otherwise, any characters beyond the n-1st are discarded rather than being written to the array and a null character is appended at the end.

snprintf() returns the number of characters that would have been assigned to s, had n been sufficiently large, not including the nul character or a negative value if an encoding error occurred. Thus, the nul-terminated output will have been completely written if and only if the returned value is nonnegative and less than n.

This facility may not be available on configurations of the EWL that run on platformswithout file systems.

Listing: Example of snprintf() Usage

#include <stdio.h>

int main()

{

int i = 1;

static char s[] = "Programmer";

char dest[50];

int retval;

retval = snprintf(dest, 5, "%s is number %d!", s, i);

printf("n too small, dest = |%s|, retval = %i\n", dest, retval);

retval = snprintf(dest, retval, "%s is number %d!", s, i);

printf("n right size, dest = |%s|, retval = %i\n", dest,

retval);

return 0;

}

Output:

n too small, dest = |Prog|, retval = 23

n right size, dest = |Programmer is number 1|, retval = 23