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".

asked Apr 1, 2014 by Lucy (990 points)

1 Answer

 
Best answer

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().
answered Apr 1, 2014 by Eric Z Ma (44,280 points)
selected Apr 1, 2014 by Lucy

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...