Logo 
Search:

C Programming Articles

Submit Article
Home » Articles » C Programming » Homework HelpRSS Feeds

Program to search and/or replace a word in C Program

Posted By: Ludwik Fischer     Category: C Programming     Views: 9483

Write a program to search and/or replace a word in C Program. It asks for an input file and 2 string. One for searching and one for replacement.If the file contains search string than it will print that line containing search string and asks for the confirmation to change it.If you say "yes" it changes it else continues till the file is over.

Code for Program to search and/or replace a word in C Program in C Programming

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

count_data();

void main()
{
   // calling function
   count_data();
   getch();
}
count_data() // function for count no of words,lines & characters.
{
   FILE *fp,*fp_rep;
   char ch,ch1,temp_str[50],rep_str[10],new_str[10];
   int count=0; // counter
   clrscr();


   fp=fopen("c:\\windows\\desktop\\input.txt","r");
   fp_rep=fopen("c:\\windows\\desktop\\input1.txt","w");

   printf("\nEnter String to find:");
   scanf("%s",rep_str);
   printf("\nEnter String to replace:");
   scanf("%s",new_str);

   while((ch=getc(fp))!=EOF)
   {
     if(ch==' ')
      {
    temp_str[count]='\0';
    if(strcmp(temp_str,rep_str)==0)
     {
      printf("Do u want to replace(y/n):");
      ch1=getche();
      if(ch1=='y')
      {
       fprintf(fp_rep," %s",new_str);
       count=0;
      }
      else
       { fprintf(fp_rep," %s",temp_str);count=0;}
     }
    else
     {
       fprintf(fp_rep," %s",temp_str);
       count=0;
      }
      }else
      {
    temp_str[count++]=ch;
      }
    }
      if(strcmp(temp_str,rep_str)==0)
     {

      printf("Do u want to replace(y/n):");
      ch1=getche();
      if(ch1=='y')
      {
       fprintf(fp_rep,"%s ",new_str);
       count=0;
      }
      else
       {
        fprintf(fp_rep,"%s ",temp_str);
        count=0;
       }
     }else
      {
       fprintf(fp_rep,"%s ",temp_str);
      }

    fclose(fp);
    fclose(fp_rep);
    remove("c:\\windows\\desktop\\input.txt");
    rename("c:\\windows\\desktop\\input1.txt","c:\\windows\\desktop\\input.txt");
    fflush(stdin);

}
  
Share: 


Didn't find what you were looking for? Find more on Program to search and/or replace a word in C Program Or get search suggestion and latest updates.

Ludwik Fischer
Ludwik Fischer author of Program to search and/or replace a word in C Program is from Frankfurt, Germany.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!