Created
July 15, 2016 18:52
-
-
Save lesovsky/d32a984f97cfcb991c54b27b5d6d3e0d to your computer and use it in GitHub Desktop.
How-to append strings using snprintf (without strcat/strncat).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#define LOC_MAXLEN 13 | |
int main (void) | |
{ | |
char dest[LOC_MAXLEN]; | |
snprintf(dest, LOC_MAXLEN, "%s%s", "abc", "def"); | |
printf("%s\n", dest); | |
/* append new string using length of previously added string */ | |
snprintf(dest + strlen(dest), LOC_MAXLEN - strlen(dest), "%s", "ghi"); | |
printf("%s\n", dest); | |
/* repeat that */ | |
snprintf(dest + strlen(dest), LOC_MAXLEN - strlen(dest), "%s", "jkl"); | |
printf("%s\n", dest); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One other approach to consider is to have a dedicated tracking variable tracking the number of characters written.
This removes the overhead of strlen.
Expected output: