#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
#define SIZE 1024
void str_replace(char *s, const char *oldStr, const char *newStr) {
char *pos, tmp[SIZE];
int index = 0, len = strlen(oldStr);
while ((pos = strstr(s, oldStr)) != NULL) {
strcpy(tmp, s);
index = pos - s;
s[index] = '\0';
strcat(s, newStr);
strcat(s, tmp + index + len);
}
}
void replace_all_occurrences(char *thefile, char *oldStr, char *newStr) {
FILE *fp, *fptmp;
char buf[SIZE], tmpfile[64] = "d:\\tmp.txt";
//char oldStr[32] = "Wo_", newStr[32] = "Aop_";
//char oldStr[32] = "$wo", newStr[32] = "$aop";
fp = fopen(thefile, "r");
fptmp = fopen(tmpfile, "w");
if (fp == NULL || fptmp == NULL) {
printf("Error open file\n");
exit(1);
}
while ((fgets(buf, SIZE, fp)) != NULL) {
str_replace(buf, oldStr, newStr);
fputs(buf, fptmp);
}
fclose(fp);
fclose(fptmp);
remove(thefile);
rename(tmpfile, thefile);
}
void replace_in_all_files(char *mainpath, char *extension, char *oldStr, char *newStr, int extension_size) {
char path[SIZE], path_file[SIZE];
struct dirent *drnt;
DIR *dir = opendir(mainpath);
if (!dir)
return;
while ((drnt = readdir(dir)) != NULL) {
if (strcmp(drnt->d_name, ".") != 0 && strcmp(drnt->d_name, "..") != 0) {
if (strcmp(drnt->d_name + strlen(drnt->d_name) - extension_size, extension) == 0) {
printf("%s\n", drnt->d_name);
strcpy(path_file, mainpath);
strcat(path_file, "\\");
strcat(path_file, drnt->d_name);
replace_all_occurrences(path_file, oldStr, newStr);
}
strcpy(path, mainpath);
strcat(path, "/");
strcat(path, drnt->d_name);
replace_in_all_files(path, extension, oldStr, newStr, extension_size);
}
}
closedir(dir);
}
int main(int argc, char **argv)
{
replace_in_all_files("d:\\test", ".c", "index", "last_index", 2);
return 0;
}
/*
run:
*/