/* bgsub.c 1.0.1 (2002-Jan-29-Tue) Adam M. Costello http://www.nicemice.net/amc/ bgsub Copies stdin to stdout, globally substituting the string for the string . The input stream and the arguments may contain binary data, but the arguments cannot contain zero-bytes (NUL characters). */ /* This is ANSI C code. */ #include #include #include static char *progname = NULL; void fail(void) { perror(progname); exit(EXIT_FAILURE); } void usage(void) { fprintf(stderr, "usage:\n" "%s \n" "Copies stdin to stdout, " "globally substituting for .\n", progname); exit (EXIT_FAILURE); } int main(int argc, char **argv) { unsigned char *old, *new, *lookingfor, *p; int c; progname = strrchr(argv[0], '/'); if (!progname) progname = argv[0]; else ++progname; if (argc != 3) usage(); old = (unsigned char *) argv[1]; new = (unsigned char *) argv[2]; lookingfor = old; for (;;) { c = getchar(); if (c == *lookingfor) { if (!*++lookingfor) { if (fputs((char *) new, stdout) == EOF) fail(); lookingfor = old; } } else { for (p = old; p != lookingfor; ++p) { if (putchar(*p) == EOF) fail(); } lookingfor = old; if (c == EOF) break; else if (putchar(c) == EOF) fail(); } } exit(EXIT_SUCCESS); }