English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

الوظائف في لغة C

القوائم في لغة C

المراجع في لغة C

ال نصوص في لغة C

C Language Structure

C Language File

C Others

C Language Reference Manual

Usage and example of C library function snprintf()

مكتبة C القياسية - <stdio.h>

C Library Function int snprintf(char *str, size_t size, const char *format, ...) Set the variable arguments (...) to be formatted into a string according to the format and copied to str, size is the maximum number of characters to be written, and if it exceeds size, it will be truncated.

Declaration

Below is the declaration of the snprintf() function.

int snprintf ( char * str, size_t size, const char * format, ... );

Parameters

  • str -- Target string.
  • size -- Copy byte count(Bytes).
  • format -- Format into a string.
  • ... -- Variable arguments.

Return Value

  • (1) If the length of the formatted string is less than or equal to size, the entire string will be copied to str, with a string terminator \0 added;
  • (2) If the length of the formatted string is greater than size, the part beyond size will be truncated, and only (size-1) characters will be copied to str, with a string terminator \0 added, and the return value is the length of the string to be written.

Online Example

The following example demonstrates the usage of the snprintf() function.

Online Example

#include <stdio.h>
 
int main()
{
    char buffer[50];
    char* s = "w3codeboxcom";
 
    // read a string and store it in buffer
    int j = snprintf(buffer, 6, "%s\n", s);
 
    // output buffer and character count
    printf("string:\n%s\ncharacter count = %d\n", buffer, j);
 
    return 0;
}

النتيجة الخارجة هي:

النص:
runoo
عدد الحروف = 10

مكتبة C القياسية - <stdio.h>