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,880 questions

51,806 answers

573 users

How to find and replace all occurrences of a string in a text file with C

1 Answer

0 votes
#include <stdio.h>
#include <string.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);
    }
}
 
int main(int argc, char **argv) 
{ 
    FILE *fp, *fptmp;
    char thefile[64] = "d:\\thefile.txt", buf[SIZE];
    char tmpfile[64] = "d:\\tmp.txt";
    char oldStr[32] = "sql", newStr[32] = "server";
 
    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);
 
    printf("Success\n");
 
    return 0;
}
 
 
/*
thefile.txt 
-----------
$server_db_username
$server_db_password
   
*/
  
 
/*
    
run:
 
 
*/

 

 



answered Jan 22, 2019 by avibootz

Related questions

...