C/Strmcatf

From Attie's Wiki
(Difference between revisions)
Jump to: navigation, search
m (Created page with 'This is a variation of <code>strcat()</code> with a few important differences / improvements: * allows you to pass a formatted string like <code>printf()</code> * automatically a…')
 
m
Line 1: Line 1:
 
This is a variation of <code>strcat()</code> with a few important differences / improvements:
 
This is a variation of <code>strcat()</code> with a few important differences / improvements:
 
* allows you to pass a formatted string like <code>printf()</code>
 
* allows you to pass a formatted string like <code>printf()</code>
* automatically allocates enough space to extend dest (a maximum of 4096 bytes at a time)
+
* automatically allocates enough memory to extend dest (a maximum of 4096 bytes at a time)
 
* returns a pointer to the <code>\0</code> at the end of dest after the operation.
 
* returns a pointer to the <code>\0</code> at the end of dest after the operation.
  

Revision as of 19:12, 13 September 2011

This is a variation of strcat() with a few important differences / improvements:

  • allows you to pass a formatted string like printf()
  • automatically allocates enough memory to extend dest (a maximum of 4096 bytes at a time)
  • returns a pointer to the \0 at the end of dest after the operation.
struct strm {
  char *s;
  int l;
};
 
char *strmcatf(struct strm *dest, char *format, ...) {
  char buf[4096];
  int blen;
  int dlen;
  int tlen;
 
  if (!dest) {
    dest = calloc(1,sizeof(struct strm));
    if (!dest) return NULL;
  }
 
  va_list ap;
  va_start(ap,format);
  vsnprintf(buf,sizeof(buf),format,ap);
  va_end(ap);
 
  if (dest->s) {
    dlen = strlen(dest->s);
  } else {
    dlen = 0;
  }
  blen = strlen(buf);
  tlen = dlen + blen;
 
  if (tlen + 1 > dest->l) {
    dest->s = realloc(dest->s,tlen);
    dest->l = tlen;
  }
 
  strncat(dest->s,buf,blen);
 
  return &((dest->s)[tlen]);
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox