Listing 3 align.c — places a string into a field with left, right, or center justification and pads with a user-supplied character

/* align.c: Align a string within a background */

#include <string.h>

#define LEFT (-1)
#define CENTER 0
#define RIGHT 1

#define min(x,y) ((x) <= (y) ? (x) : (y))

char *align(char *buf,int width,char fill,int justify,char *data)
{
   char *p;
   
   /* Truncate, if necessary */
   int dlen = min(width,strlen(data));
   
   /* Populate with fill character */
   memset(buf,fill,width);
   buf[width] = '\0';
   
   /* Calculate starting point */
   if (justify == LEFT)
      p = buf;
   else if (justify == CENTER)
      p = buf + (width-dlen)/2;
   else
      p = buf + width-dlen;
   
   /* Insert the data there */
   memcpy(p,data,dlen);
   return buf;
}
/* End of File */