How to get the directory path and file name from a absolute path in C on Linux
How to get the directory path and file name from a absolute path in C on Linux?
For example, with "/foo/bar/baz.txt", it will produce: "/foo/bar/" and "baz.txt".
You can use the APIs basename and dirname to parse the file name and directory name.
A piece of C code:
#include <libgen.h>
#include <string.h>
char* local_file = "/foo/bar/baz.txt";
char* ts1 = strdup(local_file);
char* ts2 = strdup(local_file);
char* dir = dirname(ts1);
char* filename = basename(ts2);
// use dir and filename now
// dir: "/foo/bar"
// filename: "baz.txt"
Note:
- dirnameand- basenamereturn pointers to null-terminated strings. Do not try to- freethem.
- There are two different versions of basename—the POSIX version and the GNU version.
- The POSIX version of dirnameandbasenamemay modify the content of the argument. Hence, we need tostrdupthelocal_file.
- The GNU version of basenamenever modifies its argument.
- There is no GNU version of dirname().
Hello.
I’m afraid you forgot to free an allocated memory