How to get the directory path and file name from a absolute path in C on Linux
Posted on In QAHow 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:
dirname
andbasename
return pointers to null-terminated strings. Do not try tofree
them.- There are two different versions of
basename
—the POSIX version and the GNU version. - The POSIX version of
dirname
andbasename
may modify the content of the argument. Hence, we need tostrdup
thelocal_file
. - The GNU version of
basename
never modifies its argument. - There is no GNU version of dirname().
Hello.
I’m afraid you forgot to free an allocated memory