Sample solution for assignment 1


/*
 * change.c
 *
 * Matthias Blume (blume@cs.princeton.edu)
 *
 * Usage:
 *  sample-change from [ to ]
 *
 * `from' must be non-empty and canot exceed 119 characters in length.
 * There are no further restrictions, although the output looks a bit
 * funny when the program is used interactively (because it "waits" for
 * input from the next line when it gets to the end of the previous line),
 * so input and output mix in some unintuitive way.
 */
# include <stdio.h>
# include <string.h>

# define MAX 120

int main (int argc, char **argv)
{
  char *from, *to;
  char line [MAX];
  int flen, leftover;
  char *lend, *lcur, *p;

  to = "";
  switch (argc) {
  case 3:
    to = argv [2];
  case 2:
    from = argv [1];
    break;
  default:
    fprintf (stderr, "Usage: %s from [ to ]\n", argv [0]);
    return 1;
  }

  flen = strlen (from);

  if (flen == 0) {
    fprintf (stderr, "%s: `from' string must be non-empty\n", argv [0]);
    return 2;
  } else if (flen >= MAX) {
    fprintf (stderr, "%s: `from' string must have fewer than %d characters\n",
	     argv [0], MAX);
    return 3;
  }

  leftover = 0;

  while (fgets (line + leftover, MAX - leftover, stdin) != NULL) {
    lend = line + strlen (line); /* marks end of current line */
    lcur = line;
    while ((p = strstr (lcur, from)) != NULL) {
      while (lcur < p) {
	putchar (*lcur);
	lcur++;
      }
      fputs (to, stdout);
      lcur += flen;
    }
    /* Now, if there are more than flen characters left, we output all
     * but the last flen-1 of them, because they certainly cannot
     * contain the search pattern.  All remaining caracters are moved to the
     * beginning of the line buffer. */
    while (lcur + flen <= lend) {
      putchar (*lcur);
      lcur++;
    }
    leftover = lend - lcur;
    p = line;
    while (*p++ = *lcur++)	/* move leftover string to beginning of line */
      ;
  }
  /* anything left in the buffer? */
  if (leftover > 0)
    fputs (line, stdout);

  return 0;
}

Matthias Blume, CS Department, Princeton University