Are there any C APIs to extract the base file name from its full path in Linux?

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.


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
$ 

#include <string.h>

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

Tags:

Linux

C