Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
f4c275ab7cbabecd97ff5cfe6fddb9c781ef118e
[simgrid.git] / tools / tesh2 / src / str_replace.c
1 #include <str_replace.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <stdlib.h>
5
6 #include <stdio.h>
7
8 int
9 str_replace(char** str, const char* what, const char* with)
10 {
11         int pos, i;
12         char* begin;
13         char* buf;
14          
15         if(!(begin = strstr(*str, what)))
16         {
17                 errno = ESRCH;
18                 return -1;
19         }
20         
21         pos = begin - *str;
22         
23         i = 0;
24         
25         /*while(begin[i] != ' ' && begin[i] != '\n' && begin[i] != '\r' && begin[i] != '\0')
26                 i++;
27         
28         pos += i;
29         */
30         
31         pos += strlen(what);
32         
33         if(begin == *str)
34         {
35                 if(!(buf = (char*) calloc(strlen(with) + ((pos < strlen(*str)) ? strlen(*str + pos) : 0) + 1, sizeof(char))))
36                         return -1;
37                         
38                 strcpy(buf, with);
39                 
40                 if(pos < strlen(*str))
41                         strcpy(buf + strlen(with), *str + pos);
42         }
43         else
44         {
45                 if(!(buf = (char*) calloc((begin - *str) + strlen(with) + ((pos < strlen(*str)) ? strlen(*str + pos) : 0) + 1, sizeof(char))))
46                         return -1;
47                 
48                 strncpy(buf, *str,  (begin - *str));
49                 strcpy(buf + (begin - *str) , with);
50                 
51
52                 if(pos < strlen(*str))
53                         strcpy(buf + (begin - *str) + strlen(with), *str + pos);
54         }       
55         
56         free(*str);;
57         *str = buf;
58         
59         return 0;
60  
61
62
63 int
64 str_replace_all(char** str, const char* what, const char* with)
65 {
66         int rv;
67         
68         while(!(rv = str_replace(str, what, with)));
69         
70         return (errno == ESRCH) ? 0 : -1;
71 }
72
73