Skip to content

Instantly share code, notes, and snippets.

@lesovsky
Created July 15, 2016 18:52
Show Gist options
  • Save lesovsky/d32a984f97cfcb991c54b27b5d6d3e0d to your computer and use it in GitHub Desktop.
Save lesovsky/d32a984f97cfcb991c54b27b5d6d3e0d to your computer and use it in GitHub Desktop.
How-to append strings using snprintf (without strcat/strncat).
#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;
}
@mofosyne
Copy link

mofosyne commented Feb 27, 2025

One other approach to consider is to have a dedicated tracking variable tracking the number of characters written.

This removes the overhead of strlen.

#include <stdio.h>
#include <string.h>

#define LOC_MAXLEN 13

int main (void)
{
  char dest[LOC_MAXLEN] = {0};
  unsigned int destcount = 0;

  destcount += snprintf(dest + destcount, LOC_MAXLEN - destcount, "%s%s", "abc", "def");
  printf("%s\n", dest);
  
  /* append new string using length of previously added string */
  destcount += snprintf(dest + destcount, LOC_MAXLEN - destcount, "%s", "ghi");
  printf("%s\n", dest);

  /* repeat that */
  destcount += snprintf(dest + destcount, LOC_MAXLEN - destcount, "%s", "jkl");
  printf("%s\n", dest);
  
  return 0;
} 

Expected output:

abcdef
abcdefghi
abcdefghijkl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment