by vortico · 8y ago · 0 comments
snprintf(buffer, buffer_len, "%s Stuff %s", str1, str2);
It's safe (C99, C++11) and easily extendible. Format strings are fun!
Not the fastest, but if the bottleneck of your program is concatinating strings, just do it manually. char *a;
char *b;
char *c;
strcpy(c, a);
strcat(c, b);
and I meant that `snprintf` can replace that. But if you actually only have two strings, one with a larger buffer than what it contains, and one to be concatinated, then you can't use `snprintf` like that.One day someone will do something like strncat(a += previous_delta, ...).
char* mystrncat(char *a, const char *b, size_t maxlen){
snprintf(a + strlen(a), maxlen - strlen(a), "%s", b);
return a;
}
OPTION 2 (gccism): #define strncat(_a, b, maxlen) ({char* a = _a; snprintf(a + strlen(a), maxlen - strlen(a), "%s", b); _a;}) char *x = calloc(n, 1);
strncpy(x, y, n - 1);
Which can be replaced with: char *x = strdup(y);
Which is both one line shorter and 100% less error prone!Under swprintf, and related functions, %s still takes a char pointer, not wchar_t! So when you make everything wide, you have to edit all the %s to %ls.