String Replace

This  program removes all occurence of argv[1] by argv[2] in the file argv[3].

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

/* Return the length of the file.Paramter is the file descriptor of the file */
off_t filelength(int fildes)
{
 off_t filesize;
 filesize=lseek(fildes,0,SEEK_END);
 lseek(fildes,0,SEEK_SET);
 return filesize;
}

/* Finds needle in p and if found skips needle string and print replace */
void match(char *p,const char *needle,const char *replace,size_t size)
{
 char *t;
 char *begin;
 char *c;
 int  needle_len;
 t=p ;    /* t is the current position of the buffer */
 begin=p; /* begin always point to the character from where printing starts */
 needle_len=strlen(needle);
 for(;(t-p)!=size;){

 t=strstr(t,needle);
 if(t){
 for(c=begin;c!=t;c++)/* t contains the address of needle so skip it */
 putchar(*c);
 printf("%s",replace);/* Prints replace in place of the needle string */
 t+=needle_len;       /* t now pints to the string after the match */
 begin=t;             /* Update begin to print from the charatcers after the match */
 }
 else break;
 }
 /* Prints the remaining character in the buffer which has no match with needle */
 for(c=begin;(c-p)!=size;c++)
 putchar(*c);
 //putchar('\n');
}

int main(int argc,char *argv[])
{
 if(argc!=4 && argc){
 fprintf(stderr,"Illegal number of parameters\n");
 return 1;
 }
 else
 if(argc==1){
 printf("Usage %s <string_to_replace> <string_to_replace_by>\n",argv[0]);
 return 1;
 }

 int fd;
 off_t size;
 char *chunk;
 char *needle;
 char *replace;

 needle=argv[1];  /*String to replace */
 replace=argv[2]; /*String to replace needle by */

 if((fd=open(argv[3],O_RDONLY))==-1){
 fputs("Error in opening file",stderr);
 return 1;
 }
 size=filelength(fd);
 chunk=(char*)malloc(size+1);
 if(!chunk){
 fputs("Memory intialization failure",stderr);
 return 1;
 }

 if(read(fd,chunk,size)==size)
 match(chunk,needle,replace,size);
 else {
 fputs("Error in reading file\n",stderr);
 return 1;
 }
 return 0;
}

Leave a comment