Write a program to replace one word with another word in file.
#include<stdio.h> #include<stdlib.h> #include<string.h> #include"fileinfo.h" void Word_Replace_With_Another_Word(FILE*,char*,char*); char* Replace_Word_in_String(char*,char*,char*); int FinalLength = 0; int main() { //int WordCount = 0; char file[32],wordtofind[100],wordtoreplacewith[100]; FILE *fp; printf("Enter file name = "); scanf("%[^\n]",file); fp = fopen(file,"r+"); if(fp == NULL) { printf("file is not present in this directory\n"); return 0; } printf("Word to find = "); scanf(" %[^\n]",wordtofind); printf("Word to Replace with = "); scanf(" %[^\n]",wordtoreplacewith); Word_Replace_With_Another_Word(fp,wordtofind,wordtoreplacewith); return 0; } void Word_Replace_With_Another_Word(FILE* fp,char *s,char *r) { char *p,ch; char *q=NULL; int CharCount,i=0; CharCount = Get_Total_Chars(fp); p = (char*)malloc(CharCount); while((ch = fgetc(fp)) != EOF) { p[i] = ch; i++; } p[i] = '\0'; q = (char*)malloc(sizeof(char) * FinalLength); q = Replace_Word_in_String(p,s,r); fclose(fp); fp = fopen("result","w"); fputs(q,fp); fclose(fp); } char* Replace_Word_in_String(char* s1,char *s2,char *s3) { int l1,l2,l3,i,j,m,t; l1 = strlen(s1); l2 = strlen(s2); l3 = strlen(s3); char *org,*q = NULL; org = s1; m = 0; while( q = strstr(s1,s2)) { s1=q+l2; m++; } FinalLength = l1-(l2*m)+(l3*m); s1 = org; q = (char*)malloc((sizeof(char)) * FinalLength); m = 0; for(i=0;i<l1;i++) { if(s1[i] == s2[0]) { for(j=1;j<l2;j++) { if(s1[i+j] != s2[j]) break; } if(j == l2) { for(t=0;t<l3;t++) { q[m++] = s3[t]; } s1=s1+l2-1; } else q[m++] = s1[i]; } else { q[m++] = s1[i]; } } q[m] = '\0'; return q; }
Note: File name info is present in the current working directory.
cat info It is just a random text to check the code it is wonderful let me say it is
Output
./a.out Enter file name = info Word to find = is Word to Replace with = IS
cat Result It IS just a random text to check the code it IS wonderful let me say it IS