Let's say I have the following string which looks like a file path:
char *filepath = "this/is/my/path/to/file.jpg";
I can use strrchr()
to extract file.jpg
as follows:
char *filename = strrchr(filepath, '/') + 1;
Now I need to extract and store the rest of the string this/is/my/path/to
. How do I do that in the most effective manner? Please note that I would like to avoid using strtok()
or regex
or big iterative loops.
It will be very nice if:
I can apply the same the substring extraction technique to strchr()
where I have extracted the substring this
using strchr(filepath, '/')
and now I need to extract the rest of the substring is/my/path/to/file.jpg
Copy everything up to the file name, then append a '\0'
:
int pathLen = filename - filepath;
char *path = (char *) malloc(pathLen + 1);
memcpy(path, filepath, pathLen);
path[pathLen] = '\0';
...
free(path);