Logo AND Algorithmique Numérique Distribuée

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