Write a c program using command line arguments to search for word in file and replace it with the specific word

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
FILE *fr,*fw;
int i=0,j,flag=0;
char s[20],*p,d[80];
clrscr();
if(argc!=3)
{
printf("\n error in file opening\n");
exit(0);
}
fw=fopen("a.txt","w");
fr=fopen(argv[1],"r");
if((fr==NULL)||(fw==NULL))
{
printf("error");
exit(0);
}
while(fgets(s,80,fr)!=NULL)
{
for(i=0;i<strlen(s);i++)
{
if(s[i]!='\n')
d[i]=s[i];
}
d[i-1]!='\0';
p=strtok(d," ");
while(p!=NULL)
{
printf("%s",p);
flag=0;
if(strcmp(p,argv[2])==0)
{
fputs(argv[3],fw);
flag=1;
}
if(flag==0)
fputs(p,fw);
fputs(" ",fw);
p=strtok(NULL," ");
}
fputs("\n",fw);
}
remove(argv[1]);
rename("b.txt",argv[1]);
fcloseall();
}

Comments

  1. hello
    I was trying to code prime number using command line argument. will you please help me out by writing this code.

    ReplyDelete

Post a Comment