#include <stdio.h>
#include <string.h>
extern int errno;
#define BUFFER_SIZE 200
char buffer[BUFFER_SIZE];
int
main(argc, argv)
int argc;
char **argv;
{
int length, matchChar, fileChar, cur, fileIndex, stringIndex;
char *s;
FILE *f;
if (argc != 4) {
fprintf(stderr,
"Wrong # args: should be \"%s fileName string replace\"\n",
argv[0]);
exit(1);
}
f = fopen(argv[1], "r+");
if (f == NULL) {
fprintf(stderr,
"Couldn't open \"%s\" for writing: %s\n",
argv[1], strerror(errno));
exit(1);
}
for (cur = 0; cur < BUFFER_SIZE; cur++) {
buffer[cur] = 0;
}
s = argv[2];
length = strlen(s);
if (length > BUFFER_SIZE) {
fprintf(stderr,
"String \"%s\" too long; must be %d or fewer chars.\n",
s, BUFFER_SIZE);
exit(1);
}
matchChar = s[length-1];
while (1) {
fileChar = getc(f);
if (fileChar == EOF) {
if (ferror(f)) {
goto ioError;
}
fprintf(stderr, "Couldn't find string \"%s\"\n", argv[2]);
exit(1);
}
buffer[cur] = fileChar;
if (fileChar == matchChar) {
for (fileIndex = cur-1, stringIndex = length-2;
stringIndex >= 0; fileIndex--, stringIndex--) {
if (fileIndex < 0) {
fileIndex = BUFFER_SIZE-1;
}
if (buffer[fileIndex] != s[stringIndex]) {
goto noMatch;
}
}
if (fseek(f, -length, SEEK_CUR) == -1) {
goto ioError;
}
if (fwrite(argv[3], strlen(argv[3])+1, 1, f) == 0) {
goto ioError;
}
exit(0);
}
noMatch:
cur++;
if (cur >= BUFFER_SIZE) {
cur = 0;
}
}
ioError:
fprintf(stderr, "I/O error: %s\n", strerror(errno));
exit(1);
}