Hi,
This is an existing code from a website which is supposed to find a desired string in the file and replaces it on its occurance.
I tried compiling this code n it doesn't seem to append the string Replacetext(Help) in the FILE fp. But however it does write into the FILE fout on the occurance of String SearchText(Hello). I tried adding fflush(fp) into the code . but it doesn't seem to help. can somebody figure out whats happening. I did a single step trace on the code n it does replace it. after complete execution when i open the file fp(log.txt) replaced string does not exist. i have pasted the entire piece of code. really appreciate ur help.
Code:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp,*fout;
int i=0,len_string;
char SearchText[]="Hello"; /* You can replace this text */
char ReplaceText[]="Help"; /*You can also replace this text. */
char temp[30];
fp=fopen("log.txt","a+");
fout=fopen("temp.txt","a+");
rewind(fp); /* for going to start of file. */
if(fp==NULL || fout==NULL)
{
printf("File couldn't be opened ");
exit(0);
}
len_string=strlen(SearchText);
while(!feof(fp))
{
for(i=0;i<len_string;i++) temp[i]=fgetc(fp);
temp[i]='\0';
if(stricmp(SearchText,temp)==0) /* the stricmp() is used for comparing both string. */
{
fprintf(fp,"%s ",ReplaceText);
fprintf(fout,"%s",ReplaceText);
fflush(fp);
fclose(fp);
fclose(fout);
exit(1);
}
fseek(fp,-(len_string-1),1);
}
fclose(fp);
fclose(fout);
}