Billy Billy - 3 months ago 6
C Question

Remove everything before last forward-slash (including that slash) in a C char array

I have a char array called

arg
.
arg[0]
is the path to a file. I do not know the exact path, so lets just say it's
/path/to/file
. I do not want to know the full path, I just want to know the filename (
file
in this case). So how can I remove everything before the last forward slash (including that slash), resulting in
"file"
, instead of
"/path/to/file"
, or
"alternatefile"
, instead of
"/alternatepath/to/alternatefile"
?

Here is my code:

#include <stdio.h>
int main(int argc, char *argv[]) {
char *arg[] = argv;
// This is where I need code to trim everything before the last forward-slash
printf("%s\n", arg[0]);
}


So I need something like
arg[0] = strtrm(everythingbefore, "/", arg[0]);

Answer

Here is a simple solution:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *base = strrchr(argv[0], '/');
    if (base) {
        base += 1;
    } else {
        base = argv[0];
    }
    printf("%s\n", base);
    return 0;
}