I have a char array and I want to replace 1*
or 2*
for myDirectory1
or myDirectory2
Ex: C:/1*/file.txt
-> C:/MDirectory1/file.txt
Ex: C:/2*/file.txt
-> C:/MDirectory2/file.txt
My code seems to works but I do not understand some things:
Is okay to initialize a dynamic char array like this?
char *cad = (char*)malloc(sizeof(char) * 15);
if (!cad) exit(1);
Is okay to use realloc when I want to insert the char array inside the other?
realloc(*cad, sizeRep + strlen(auxi) + 1);
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *replaceString(char **cad) {
int sizeRep;
char *auxi = *cad, *plec;
char replace[500];
plec = strchr(*cad, '*');
switch (*(plec - 1)) {
case '1':
strcpy(replace, "myDirectory1");
break;
case '2':
strcpy(replace, "MyDirectory2");
}
sizeRep = strlen(replace);
realloc(*cad, sizeRep + strlen(auxi) + 1);
memmove(plec + strlen(replace) - 1, plec + 1, strlen(plec));
memmove(plec - 1, replace, sizeRep);
return auxi;
}
int main() {
char *cad = (char*)malloc(sizeof(char) * 15);
if (!cad) exit(1);
strcpy(cad, "C:/2*/file.txt");
printf("%s", replaceString(&cad));
return 0;
}