hi every body
can some one help me with thi problem
i have a text file which is following
hi Hello this is my Hello to
the Hello world
i write a code in c which is following
#include<stdio.h>
#include<string.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("ram.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(strcmp(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);
}
}
fclose(fp);
fclose(fout);
}
now my out put is like that
hi Hello this is my Hello to
the Hello world
Help Help
what i m doing wrong ?
how to replace Hello to help in my text file ?
how to get my output like that?
hi Help this is my Hello to
the Help world
can anybody explain with code ?
For your input file, you should use "r" (read-only). Does your output file exist already? If so, you will want to open it with r+. If not, you will need to write all of the contents from your input file to the output file.
Also, you should move your rewind( fp ) to after you check for a null pointer.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max_temp 30
int main()
{
FILE *fp,*fout;
int i;
char SearchText[]="Hello"; /* You can replace this text */
char ReplaceText[]="Help"; /*You can also replace this text. */
char temp[max_temp];
fp=fopen("ram.txt","r"); //"r" opens file at the begining -> no need for rewind( fp )
fout=fopen("temp.txt","w");
if(fp==NULL || fout==NULL){
perror("File couldn't be opened ");
}
fscanf(fp,"%s",temp);
while(!feof(fp)){
if(strcmp(SearchText,temp)==0)
fprintf(fout,"%s ",ReplaceText);
else
fprintf(fout,"%s ",temp);
fscanf(fp,"%s",temp);
}
fclose(fp);
fclose(fout);
return 0;
}
Don't use fscanf like that. What if it reads more than can fit in temp? You'll have a buffer overrun. If you insist on using it, at least pass fscanf how much it should read: