Hello,
I am writing a program that uses command line argument for string replacement:
a sample run of the program should be like:
programname.out I like studying like hate
outputs:
I hate studying.
here is the code I wrote :
It is giving Segmentation fault error.
could you please modify the code for me so it works.
thanks
Code:
#include <stdio.h>
#include <string.h>
int main (int argc,char *argv[]) {
char *p, *find, *replace;
p = argv[1];
find =argv[2];
replace =argv[3];
size_t len=strlen(p);
size_t s_len=strlen(find);
size_t r_len=strlen(replace);
char *current=p;
while ((current = strstr(p,find))) {
memmove(current + r_len , current + s_len,len - (current - p) - s_len + 1);
memcpy(current, replace, r_len);
}
++p;
printf("%s\n",argv[1]);
}
Additional Details
This is another version that does not use command line arguments...
It works fine :
Code:
#include <stdio.h>
#include <string.h>
int main () {
char str[1000];
char search[10];
char replace[10];
gets(str);
gets(search);
gets(replace);
size_t len = strlen(str);
size_t s_len = strlen(search);
size_t r_len = strlen(replace);
char *current = str;
while (current = strstr(current, search)) /*assignment*/ {
memmove(current + r_len , current + s_len,len - (current - str) - s_len + 1);
memcpy(current, replace, r_len);
++current;
}
printf("%s",str);
}