there you go:
Code:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
char* strreplace(char *str, char *patt, char *repl);
int main(int argc, char** argv) {
char *str; //replace pattern
char *somestr;
size_t rsize; //num of read files by getline()
int nbytes;
char *patt = argv[1]; //pattern to look for
char *repl = argv[2]; //replace found pattern with this
while(1) {
str = NULL; //getline() needs NULL and 0 in order to allocate new mem
somestr = NULL;
rsize = 0;
if((nbytes = getline(&str, &rsize, stdin)) < 0) { //end of file
break;
}
if( argc == 3 && (strstr(str, patt) != NULL) ) {
somestr = strreplace(str, patt, repl); //this function replaces patt with repl
free(str);
printf("str: %s", somestr);
}
free(somestr);
}
return (EXIT_SUCCESS);
}
//replace all patt with repl in str
char* strreplace(char *stri, char *patt, char *repl) {
char *occ = NULL; //ptr to first char of first occurence of the pattern in str
char *temp; //temp string to hold str
int poss, pose; //poss - pos of the first char of patt in str, pose - after last char of patt
int diff = (strlen(repl) - strlen(patt));
int tempsize;
char* str = (char*)malloc(sizeof(char)*(strlen(stri) + 1));
strcpy(str, stri);
while((occ = strstr(str, patt)) != NULL) {
tempsize = strlen(str) + diff + 1;
temp = (char*)malloc(sizeof(char)*(tempsize));
poss = strlen(str) - strlen(occ); //getting the pos of the first char of patt in str
pose = poss + strlen(patt); //getting pos of the char after last char of patt in str
memcpy(temp, str, poss);
memcpy(temp + poss, repl, strlen(repl));
memcpy(temp + poss + strlen(repl), str + pose, strlen(&(str[pose])));
temp[tempsize] = '\0';
free(str);
str = (char*)malloc(sizeof(char)*tempsize);
memcpy(str, temp, tempsize);
free(temp);
}
return str; //success
}