snprintf function Usage

Source: Internet
Author: User

Function prototypes

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

Function

A variable parameter (...) Formats the string as format and then copies it to Str

(1) If the string length < size is formatted, copy the string to str and add a string terminator (' + ') to it;

(2) If the formatted string length >= size, only the (size-1) characters are copied to STR, followed by a string terminator (' + '), and the return value is the length of the string to be written.

return value

Returns the length of the string to be written if successful, or a negative value If an error occurs.

Description

strcpy () sprintf () strcat () has security implications, no cross-border checks, and its corresponding security version is:

strncpy () snprintf () Strncat ()

As an example,

#include <stdio.h> #include <stdlib.h>int main () {char str[10]={0};  int nlen=snprintf (str,sizeof (str), "0123456789012345678");  printf ("str=%s\n", str);  printf ("nlen=%d\n", Nlen); return 0;}

Run results


snprintf function Usage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.