vsnprintf_s, vsnwprintf_s

From RAD Studio
Jump to: navigation, search

Go Up to stdio.h Index


Header File

stdio.h

Category

Formatted input/output functions

Prototype

int vsnprintf_s(char * restrict s, rsize_t n, const char * restrict format, va_list arg);

int vsnwprintf_s(wchar_t * restrict s, rsize_t n, const wchar_t * restrict format, va_list arg);

Description

Replaces vsnprintf, vsnwprintf adding security enhancements.

vsnprintf_s is equivalent to vsnprintf, vsnwprintf, except that it brings explicit run-time constraints regarding the validity of s and format. Also, n must be not equal to zero and must be smaller than RSIZE_MAX, and every argument in the argument list corresponding to a %s format specifier must not be a null pointer.

In case of an error, vnsprintf_s sets '\0' to s[0].

vsnprintf_s, unlike vsprintf_s, vswprintf_s, will truncate the result to the length of the array that s is pointing to.

If the number of bytes to output is:

  • < nsize, then all of the characters have been written, including the terminating '\0' character.
  • == nsize, then nsize characters are written, with no terminating '\0' character.
  • > nsize, then only nsize characters are written, with no terminating '\0' character.

If nsize is 0, then the string will not be written to (and may be NULL.)

Return Value

Number of characters output, or, if nsize is zero, the number of bytes needed, not including the terminating '\0' character.

'\0' is written only if the return value is greater than zero and smaller than n.

Example

#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
char buffer[80];
int vspf(char *fmt, ...)
{
   va_list argptr;
   int cnt;
   va_start(argptr, fmt);
   cnt = vsnprintf_s(buffer, 70,fmt, argptr);
   va_end(argptr);
   return(cnt);
}
int main(void)
{
   int inumber = 30;
   float fnumber = 90.0;
   char string[4] = "abc";
   vspf("%d %f %s", inumber, fnumber, string);
   printf_s("%s\n", buffer);
   return 0;
}

See Also