FidoNet Echomail Archive
aust_c_here

<<< Previous Index Next >>>

From: David Nugent
To: Joshua Marshall
Date: 1996-12-23 15:48:40
Subject: sprintf function

 > > Can somebody tell me the easiest way to do this:
 > > I want to insert a character into a string.  I have tried:
 > >   sprintf(string, "%c%c%s", string[0], '0', string+1);

Ouch! You can't sprintf() a string back into itself. that's one fancy way
of committing suicide. :-)

Does your compiler implement memmove() or does your memcpy() handle
overlapping regions correctly?  If so:

/* Public domain
 */

#include <string.h>

#define TESTMAIN        /* remove this to dump main() */

int
strinsert(char * buf, int at, char const * toinsert, int buflen)
{
  int tomove, ilen, blen;

  blen = strlen(buf);
  if (at < 0 || at >= blen) /* Can't insert above/below string */
    return -1;
  tomove = blen - at;
  ilen = strlen(toinsert);
  if (blen + ilen >= buflen)    /* Insert can't overflow */
    return -1;
  memmove(buf + at + ilen, buf + at, tomove + 1); /* With NUL */
  memmove(buf + at, toinsert, ilen);
  return blen + ilen;
}

int
strdelete(char * buf, int at, int chars)
{
  int tomove;
  int blen = strlen(buf);
  if (at < 0 || at > blen)
    return -1;
  tomove = blen - at;
  if (chars > tomove)         /* Can't delete more than we have */
    chars = tomove;
  memmove(buf + at, buf + at + chars, tomove+1);  /* With NUL */
  return blen - chars;
}

#if defined(TESTMAIN)
#include <stdio.h>
int
main()
{
  char mystr[256] = "This test might work";

  printf("%s\n", mystr);
  strdelete(mystr, 10, 5);
  printf("%s\n", mystr);
  strinsert(mystr, 10, "will", 256);
  printf("%s\n", mystr);
  return 0;
}
#endif

--- MaltEd/2 1.0.b6
 * Origin: Unique Computing Pty Limited (3:632/348)
SEEN-BY: 50/99 620/243 623/630 632/103 107 271 348 360 601 635/301 544 728
SEEN-BY: 639/252 640/820 711/410 413 808 809 932 934 712/311 505 506 515 517
SEEN-BY: 712/624 704 824 841 713/317 714/906 800/1
@PATH: 632/348 360 50/99 712/624 711/808 934


<<< Previous Index Next >>>