Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to find and replace all occurrences of a string in all text files in a directory include subdirectories with C

1 Answer

0 votes
#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:


*/

 

 

 



answered Jan 22, 2019 by avibootz
edited Jan 23, 2019 by avibootz
...