Billy Billy - 1 year ago 77
C Question

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

I have a char array called

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

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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download