User Tools

Site Tools


Programming Reference/Librarys

Question & Answer

Q&A is closed

to support this page (eg 0,42 € or so) Thanks.


#include <stdio.h> /* including standard library */
//#include <windows.h> /* uncomment this for Windows */
int snprintf(char *restrict s, size_t n, const char *restrict format, ...);

description of snprintf

The function snprintf() format the format specified by arguments of the printf format specification and writes the result to the specified string by dest. size specifies the maximum length of the string at least. The string in least receive in any case a terminating NULL character. In no case is dest [destsize - 1] also written.

The return value is the number of characters that would have been written if the string would be least long enough.

To avoid buffer overflows, use this function over strcat strcpy, strncpy and strncat are preferred, since it is costly for the latter functions to be held on the remaining available space in the string Array.

C Sourcecode Example

 * snprintf example code
#include <stdio.h>
int main ( void )
  char buffer[80];
  char string[20]  = "ford prefect";
  char string2[50] = "a hoopy frood who really knows where his towel is";
  int count;
  count = snprintf ( buffer, sizeof(buffer), "The Answer is %d", 6*7 );
  snprintf ( buffer+count, sizeof(buffer)-count, ", can you tell me the question for %d.", 42 );
  printf("%s\n", buffer);
  // or another example | hint the string is shorter by 52 characters 
  if (snprintf(buffer, sizeof(buffer) - 52, "%s: %s", string, string2) >= sizeof(buffer)) {
      fprintf(stderr, "Failure: String is to long.\n");
      return 1;
    printf("%s\n", buffer);
  return 0;

fopen output example

  The Answer is 42, can you tell me the question for 42.
  ford prefect: a hoopy frood
c/stdio.h/snprintf.txt · Last modified: 2013/02/25 15:56 by