Listing 10 Functions to build strings backwards

/* preprint.c: Functions to prepend strings */

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

int prepend(char *buf, unsigned offset, char *new_str)
{
   int new_len = strlen(new_str);
   int new_start = offset - new_len;
   /* Push a string onto the front of another */
   if (new_start >= 0)
      memcpy(buf+new_start,new_str,new_len);
   
   /* Return new start position (negative if underflowed) */
   return new_start;
}

int preprintf(char *buf, unsigned offset, char *format, ...)
{
   int pos = offset;
   char *temp = malloc(BUFSIZ);
   
   /* Format, then push */
   if (temp)
   {
      va_list args;
      
      va_start(args,format);
      vsprintf(temp,format,args);
      pos = prepend(buf,offset,temp);
      va_end(args);
      free(temp);
   }
   return pos;
}

/* End of File */