tags:

views:

82

answers:

3

I guess the title says it all. Given the full path, the API should give me the base file name. E.g., "/foo/bar.txt" --> "bar.txt".

+2  A: 

There's basename() .

Feed it with a path (in the form of a char*) and it will return you the base name (that is the name of the file/directory you want) in the form of another char* .

EDIT:

I forgot to tell you that the POSIX version of basename() modifies its argument. If you want to avoid this you can use the GNU version of basename() prepending this in your source:

#define _GNU_SOURCE
#include <string.h>

In exchange this version of basename() will return an empty string if you feed it with, e.g. /usr/bin/ because of the trailing slash.

klez
strdup-ing the path before feeding it to basename() instead.
Rajorshi
yeah, good point
klez
+2  A: 

You want basename(), which should be present on pretty much any POSIX-ish system:

http://www.opengroup.org/onlinepubs/000095399/functions/basename.html

#include <stdio.h>
#include <libgen.h>

int main() {
  char name[] = "/foo/bar.txt";
  printf("%s\n", basename(name));
  return 0;
}

...

$ gcc test.c
$ ./a.out
bar.txt
$ 
Nicholas Knight
basename is destructive and will cause a segfault in this case, try `basename("/foo/bar/")`.
roe
@roe: Actually it _may_ segfault in _that_ case. In my case, it was fine. :) But you're right, fixed.
Nicholas Knight
@Nicholas; yes, naturally, sorry. I meant it MIGHT segfault in your case, assuming the string literal is some compile-time macro or something. The whole point being it might be destructive, and you're forced to make a copy of your string.
roe
+1  A: 
#include <string.h>

char *basename(char const *path)
{
    char *s = strrchr(path, '/');
    if (!s)
        return strdup(path);
    else:
        return strdup(s + 1);
}
Matt Joiner