341008
341008

Reputation: 10232

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

Given the full path, the API should give me the base file name. E.g., "/foo/bar.txt" --> "bar.txt".

Upvotes: 16

Views: 20774

Answers (4)

Matt Joiner
Matt Joiner

Reputation: 118500

#include <string.h>

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

Upvotes: 8

pan1nx
pan1nx

Reputation: 479

I think the correct C code of @matt-joiner should be:

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

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

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.

Upvotes: 11

Nicholas Knight
Nicholas Knight

Reputation: 16045

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
$ 

Upvotes: 5

Related Questions