Comments on this program please...

Martin Minow minow at decvax.UUCP
Fri Dec 6 09:30:00 AEST 1985


I posted a "better" version a week ago, but got no flames, so
it might have disappeared.  I don't like the program because it

(1) doesn't work, as noted already: fooRROUTEbar.

(2) doesn't separate form from function: I can't see how to
    adapt the program for some other keyword.  (Do I change
    the variable names, for example?)

(3) doesn't present the algorithm -- such as it is -- clearly.

(4) (3) makes fixing (1) harder.

My (somewhat more efficient) version is appended.

Martin Minow
decvax!minow

/*
 * This program reads an arbitrary file, inserting a newline
 * before every occurance of the string "ROUTE".  It is
 * written so as to easily generalize to other strings.
 * Properly resetting state where bytes in string reoccur
 * is left as an exercise for the reader.
 */

#include <stdio.h>
char	*string = "ROUTE";	/* May be varied		*/

main() {
	register int	c;
	register char	*state;

	state = string;
	do {
	    if ((c = getchar()) == *state) {
		if (*++state == '\0') {		/* Whole string?	*/
		    printf("\n%s", string);	/* Found		*/
		    state = string;
		}
	    }
	    else {
		if (state > string) {		/* Partial match?	*/
		    printf("%.*s", state - string, string);
		    state = string;		/* Reset state pointer	*/
		    if (c == *state) {		/* handle fooRROUTEbar	*/
			++state;		/* Aha! saw first byte	*/
			continue;		/* Continue scanning	*/
		    }
		}
		if (c != EOF)			/* Output non-matcher	*/
		    putchar(c);
	    }
	} while (c != EOF);
}



More information about the Comp.lang.c mailing list