C/Strncatf
From Attie's Wiki
(Difference between revisions)
(Created page with 'This is a variation of <pre>strcat()</pre> that allows you to pass a formatted string like <pre>printf()</pre> and max length for dest, not for how much of src to use. <source la…') |
m (Attie moved page Strncatf to C/Strncatf) |
||
(6 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
− | This is a variation of < | + | 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> | ||
+ | * takes a max length for dest, not for how much of src to use (like <code>strncat()</code>) | ||
+ | * returns a pointer to the <code>\0</code> at the end of dest after the operation. | ||
+ | |||
<source lang="c"> | <source lang="c"> | ||
char *strncatf(char *dest, int length, char *format, ...) { | char *strncatf(char *dest, int length, char *format, ...) { | ||
Line 9: | Line 13: | ||
length -= strlen(dest); | length -= strlen(dest); | ||
strncat(dest,buf,length-1); | strncat(dest,buf,length-1); | ||
+ | return &dest[strlen(dest)]; | ||
} | } | ||
</source> | </source> |
Latest revision as of 17:06, 14 February 2013
This is a variation of strcat()
with a few important differences / improvements:
- allows you to pass a formatted string like
printf()
- takes a max length for dest, not for how much of src to use (like
strncat()
) - returns a pointer to the
\0
at the end of dest after the operation.
char *strncatf(char *dest, int length, char *format, ...) { char buf[4096]; va_list ap; va_start(ap,format); vsnprintf(buf,sizeof(buf),format,ap); va_end(ap); length -= strlen(dest); strncat(dest,buf,length-1); return &dest[strlen(dest)]; }