Showing posts with label find and replace string from outside of the file. Show all posts
Showing posts with label find and replace string from outside of the file. Show all posts

Thursday, August 6, 2009

find and replace particular string from outside of the file

input:
1.open a .txt file .
2. type something with "hello" word.
3.close the file.
4.copy their file path.
5.paste it in fopen line.
6.replaceable word is "hi"..note: if you change this word .you should alter the for loop condition.
7.run this program with conio.h file function like clrscr();getch(); to the appropriate place.

//find and replace string from outside of the file.
#include"stdio.h"
void main(void)
{
FILE *ft;
char k,ch,replace[3],find[6];
find="hello";
replace="hi";
k=' ';
int i=1,noc=0;
ft=fopen("C:\\KARTHI\\tc\\tmp\\record.txt","r+");
if(ft==NULL)
{
puts("cannot open file\n");
exit(-1);
}else
puts("file is available\n");
while(1)
{
ch=getc(ft);
if(ch==EOF)
break;
else if(ch==find[0])
{
for(i=1;i<=4;i++)
{
if(find[i]!=getc(ft))
{
fseek(ft,-i,SEEK_CUR); goto flag;
}
}
fseek(ft,-(i),SEEK_CUR);
for(i=0;i<=1;i++)
fputc(replace[i],ft);
for(i=2;i<=4;i++) fputc(k,ft);
}
flag:noc++;
}
printf("%s",find);
fclose(ft);
printf("\ntotal number of character%d\n",noc);
}

output: 1.after run this program;
2.open that .txt file. if file exit any "hello" string, then that will replaced as "hi ".
3.Otherwise no change in the contents.