Hi,
This is an existing code from this site 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>
conio.h isn't a standard header file. I have no idea what the header file does since it doesn't exist on my computer.
Code:
#include<stdlib.h>
void main()
void main() isn't recognized by the GNU C compiler on my Linux box.
Code:
{
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];
30 is a what is known as a "magic number"
Code:
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);
}
printf() isn't going to get flushed() on the next call.
Code:
len_string=strlen(SearchText);
while(!feof(fp))
You end up reading the string twice before you reach EOF.
Code:
{
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);
}