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:

  1. dirname and basename return pointers to null-terminated strings. Do not try to free them.
  2. There are two different versions of basename—the POSIX version and the GNU version.
  3. The POSIX version of dirname and basename may modify the content of the argument. Hence, we need to strdup the local_file.
  4. The GNU version of basename never modifies its argument.
  5. There is no GNU version of dirname().

Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *