#include #include void findreplace(char *str, const char *oldword, const char *newword); int main(int argc, char *argv[]) { // ./a.out filename oldWord newWord if (argc != 4) { printf("usage: %s filename oldword newword\n", argv[0]); return 1; } char *filename = argv[1]; char *oldWord = argv[2]; char *newWord = argv[3]; if (!strcmp(oldWord, newWord)) { printf("error: words are the same\n"); return 1; } FILE *file = fopen(filename, "r"); FILE *tmpf = fopen("tmp.txt", "w"); if (!file || !tmpf) { printf("could not open files\n"); return 1; } size_t size = 256; char buf[size]; // loop while ((fgets(buf, size, file)) != NULL) { //printf("%s", buf); findreplace(buf, oldWord, newWord); fputs(buf, tmpf); } fclose(file); fclose(tmpf); remove(filename); rename("tmp.txt", filename); return 0; } void findreplace(char *str, const char *oldword, const char *newword) { char *pos, tmp[256]; int index = 0; int oldLen = strlen(oldword); while ((pos = strstr(str, oldword)) != NULL) { strcpy(tmp, str); index = pos - str; str[index] = '\0'; strcat(str, newword); strcat(str, tmp + index + oldLen); } }