Are there any C APIs to extract the base file name from its full path in Linux?
Given the full pat开发者_运维技巧h, the API should give me the base file name. E.g., "/foo/bar.txt" --> "bar.txt".
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.
#include <string.h>
char *basename(char const *path)
{
char *s = strrchr(path, '/');
if (!s)
return strdup(path);
else
return strdup(s + 1);
}
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
$
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); } }
精彩评论