C Linux Code for grepping pattern and replacing with other word

/* C Linux Code for counting  the repeated words in a file and replace it with another word*/
#include<stdio.h>
#include<string.h>

void repeatCount();

int main()
{
repeatCount();
return 0;
}

void repeatCount()
{
FILE *fp,*fp2;
fp=fopen("m1.txt","r");
fp2=fopen("m2.txt","w");
char ch;
char str_rep[20];
char str_temp[20];
char str_new[20];
int count=0;
int wordcount=0;

printf("Enter word to look for repeat:\n");
scanf("%s",str_rep);
printf("Enter word to replace wirh:\n");
scanf("%s",str_new);

while((ch=getc(fp))!=EOF)
{
//printf("\ninside while\n");
if(ch==' ')
{
// printf("inside ch=\n");
str_temp[count]='\0';

if(strcmp(str_temp,str_rep)==0)
{
//printf("inside strcmp\n");
wordcount++;
fprintf(fp2," %s",str_new);
count=0;
}
else
{
//printf("inside else of strcmp\n");
fprintf(fp2," %s",str_temp);
count=0;}
}//if(ch=' ') ends
else// else of ch=' '
{
str_temp[count++]=ch;
}

}//while endsi

printf("The word %s repeats %d times.\n",str_rep,wordcount);

fclose(fp);
fclose(fp2);
fflush(stdin);
}//repeatCount ends

No comments:

Post a Comment