Program to find a sub string and replace it with another string.

#include <stdio.h>
#include <string.h>

#define MAX 50

int main()
{
char word[MAX][MAX], sword[MAX], nword[MAX], fname[MAX], punct[MAX];
int i, n;
FILE *in, *out;

printf("Enter the filename: ");
scanf("%s",fname);

printf("Enter the word to be searched: ");
scanf("%s",sword);
printf("Enter the new word with which the old word is to be replaced: ");
scanf("%s",nword);

in=fopen(fname,"r");

i=0; n=0;
while(!feof(in))
{
fscanf(in,"%s",word[n]);
punct[n]=fgetc(in);

if(!strcmp(sword,word[n]))
strcpy(word[n],nword);
n++;
}

fclose(in);
printf("Now finished reading...\n");

printf("Write output to: ");
scanf("%s",fname);
printf("Writing output to: %s ...\n",fname);
out=fopen(fname,"w");
for(i=0;i<n-1;i++)
fprintf(out,"%s%c",word[i],punct[i]);

printf("Now finished writing...\n");
fclose(out);
printf("Done.\n");

return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s