Search code examples
carraysstringpointersmemset

I want to use memset to remove some characters from string


I used memset() to remove text.txt from path string, but the below code is not working.

Please let me know what is the problem.

char *path = "tt/tt/tt/text.txt";
char *direc = "";
int minus = 0;
int i;

for (i = strlen(path) - 1; i > 0; i--)
{ 
    if (path[i] == '/')
        break;
    else
        minus++;
}
memset(path + i, '\0', strlen(path) - minus);

printf("%s", path);

return 0;

Solution

  • The problem here is, path points to a string literal, which is usually present in read-only memory. You may not change the content of that.

    Instead, try using an array like

    char path[ ] = "tt/tt/tt/text.txt";