Saturday, August 8, 2009

Find and Replace Any String Outside of The File


#include"stdio.h"
#include "string.h"

void updateblank(FILE *, int);

void main(void)
{
FILE *ft;
static char k,ch,replace[30],find[30];
int l1,l2,j,i,noc=0,nf=0;
printf("enter the string want to be find\n");
gets(find);
printf("enter the string WITH SAME CHAR LENGTH want to be replace\n ");
gets(replace);
l1=strlen(find);
l2=strlen(replace);
printf("%d%d\n",l1,l2);

k=' ';

ft=fopen("C:\\KARTHI\\tc\\tmp\\record.txt","r+");
if(ft==NULL)
{
puts("cannot open file\n");
exit(-1);
}
puts("file is available\n");

while(1)
{

ch=getc(ft);
if(ch==EOF)
break;
if(ch==find[0]){
int isSuccess=1; //true
for(i=1;i<l1;i++)
{
if(find[i]!=getc(ft))
{
fseek(ft,-i,SEEK_CUR);
isSuccess=0;
break;
}
}

if(isSuccess)
{
nf++;
printf("\nfound\n") ;
fseek(ft,-(i),SEEK_CUR);
if(l1>l2)
{
for(i=0;i<l2;i++)
fputc(replace[i],ft);
for(i=l2;i<l1;i++)
fputc(k,ft);
}
else{
for(i=0;i<l1;i++)
fputc(replace[i],ft);

updateblank(ft,l2-l1);

for(i=l1;i<l2;i++)
fputc(replace[i],ft);
}
}

}
noc++;
}
printf("%s to %s\n",find,replace);

fclose(ft);
if(nf==0)
printf("\nno match found\n");
else printf("\nno. of match found=%d",nf);
printf("\ntotal number of character%d\n",noc);



}



void updateblank(FILE *ft, int len)
{
char ch;
int noc=0;
while(1)
{

ch=getc(ft);
if(ch==EOF)
break;
noc++;
}

char rch[noc];

fseek(ft,-(noc),SEEK_CUR);

for(int i=0;i<noc;i++)
{
rch[i]= getc(ft);
}

fseek(ft,-(noc),SEEK_CUR);

for(int i=0;i<len;i++)
{
fputc('\0',ft);
}

for(int i=0;i<noc;i++)
{
fputc(rch[i],ft);
}

fseek(ft,-(noc+len),SEEK_CUR);


}

No comments:

Post a Comment