C language according to the variable parameter synthesis string implementation code

  • 2020-04-02 00:55:55
  • OfStack

When writing code, you often need to get a specific string based on the parameters. Call vsprintf every time, malloc is annoying. Here's one
The interface of this function is implemented.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
char *xm_vsprintf_ex(int len, char *fmt, ... );
int main(int argc, char *argv[])
{
 char *ptr;
 ptr = xm_vsprintf_ex(100, "%s-%s-%s", "lias", "dzq", "lvo");
 printf("%sn", ptr);
 free(ptr);
 return 0;
}
char *xm_vsprintf_ex(int len, char *fmt, ... )
{
 va_list ap;
 char *ptr;
 ptr = (char *)malloc(len * sizeof(char));
 if(ptr == NULL)
 {
  fprintf(stderr, "malloc failedn");
  return NULL;
 }
 memset(ptr, 0, len);
 va_start(ap, fmt);
 vsprintf(ptr, fmt, ap);
 va_end(ap);
 ptr[len-1] = '0';
 return ptr;
}

It's still fun to use.


Related articles: