/*
* bsed.c - a simple stream editor.
* Copyright (C) 1998, Steven G. Isaacson
*/
#include <stdio.h>
#define BUFSIZE 1024
main(argc, argv)
int argc;
char *argv[];
{
int i, n, n2, len1, len2;
char buf[BUFSIZE];
/* If incorrect command-line arguments, display usage. */
if (argc != 3) {
fprintf(stderr,
"Usage: bsed [oldstring][newstring]\n");
fprintf(stderr,
" binary sed. reads stdin, writes stdout\n");
exit(1);
}
len1=strlen(argv[1]);
len2=strlen(argv[2]);
if (len1 > BUFSIZE) {
fprintf(stderr,
"Error: oldstring greater than BUFSIZE: %d\n",
BUFSIZE);
exit(1);
}
while ((n=read(0, buf, BUFSIZE)) > 0) {
/* Is there even the possibility of a match? */
if (memchr(buf, argv[1][0], n) == NULL) {
write(1, buf, n);
continue;
}
for (i=0; i<n; i++) {
if (buf[i] == argv[1][0]) {
if (i != 0) {
/* Pass on the non-matching characters */
write(1, buf, i);
memmove(buf, &buf[i], n - i);
/* Fill up the buffer again */
n2=read(0, &buf[n - i], BUFSIZE - (n - i));
/* Reset n, and i */
n = (n - i) + (n2 > 0 ? n2 : 0) ;
i=0;
}
/* Do we have a match? */
if (n >= len1 && memcmp(buf,argv[1],len1) == 0) {
write(1, argv[2], len2);
memmove(buf, &buf[len1], n - len1);
n = n - len1;
}
}
}
write(1, buf, n);
}
exit(0);
}
/* End of File */