snprintf, snwprintf

De RAD Studio
Aller à : navigation, rechercher

Remonter à Stdio.h - Index


Header File

stdio.h

Category

Memory and String Manipulation Routines

Prototype

int snprintf(char* buffer, size_t nsize, const char* fmt, ...);

int snwprintf(wchar_t* buffer, size_t nsize, const wchar_t* fmt, ...);

Description

Sends formatted output to a buffer of a maximum length specified by nsize.

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 bytes output, or, if nsize is 0, the number of bytes needed, not including the terminating '\0' character.

Example

#include <stdio.h>
#include <stdlib.h>

int main()
{
	//creating a buffer from multiple formats
	char buff[100];
	char str[]="hello world!";
	char c='!';
	int i=123;
	double d=23.3432;
	int bf_len=sizeof(buff)/sizeof(buff[0])-1;
	int buff_left, buff_used;
	buff_used=0;
	buff_left=bf_len-buff_used;
	int buff_written;
 buff_written = snprintf(&buff[buff_used], buff_left, "%s\n", str );
  //update the buffer
   if (buff_written >= 0)
   {
	buff_used += buff_written;
	buff_left -= buff_written;
	}
  if (buff_left>0) {
   buff_written = snprintf(&buff[buff_used], buff_left, "%c\n", c );
  //update the buffer
   if (buff_written >= 0)
   {
	buff_used += buff_written;
	buff_left -= buff_written;
	}
  }
   if (buff_left>0) {
   buff_written = snprintf(&buff[buff_used], buff_left, "%d\n", i );
  //update the buffer
   if (buff_written >= 0)
   {
	buff_used += buff_written;
	buff_left -= buff_written;
	}
  }
	if (buff_left>0) {
   buff_written = snprintf(&buff[buff_used], buff_left, "%f\n", d );
  //update the buffer
   if (buff_written >= 0)
   {
	buff_used += buff_written;
	buff_left -= buff_written;
	}
  }
  printf("The buffer:\n%s\n", buff );
  printf("The buffer has %d bytes", buff_used);
	return 0;
}

Voir aussi