0

This question may be a bit naive, but I'm wondering if it's possible to obtain the directory part of a filename in C code. For instance, say I have the following Linux file:

/home/user/Documents/Work/report.txt

and I want to obtain the string "/home/user/Documents/Work/"

Are there any C functions to do such a thing? Also, even though I gave a Linux file as an example, I'd like to be able to obtain the directory listing of a file on any OS.

Thank you in advance.

3
  • Look at strrchr().
    – pmg
    Commented May 1, 2013 at 10:53
  • It looks like strrchr() would be more useful to locate the basename of a file rather than its directory. How would you use it to find the directory?
    – Decave
    Commented May 1, 2013 at 10:56
  • @Decave You NUL-terminate the string at the position returned by strrchr(). But really, use the right tool for the task - dirname(). See my answer.
    – user529758
    Commented May 1, 2013 at 10:57

2 Answers 2

2

Use strrchr() and replace the last separator character with a '\0'

#define PATH_SEPARATOR_CHAR '/'
char text[10000] = "/home/user/Documents/Work/report.txt";
char *last = strrchr(text, PATH_SEPARATOR_CHAR);
if (last) {
    *last = 0;
    printf("path is '%s'\n", text);
} else {
    printf("Invalid text\n");
}
0

This is what the dirname() function is for:

char path[] = "/var/www/index.html";
char *dirn = dirname(path);
printf("Dirname: %s\n", dirn);
3
  • 1
    Note: dirname() (even though it does what OP wants) is not described by the C Standard.
    – pmg
    Commented May 1, 2013 at 10:58
  • @pmg I believe it's POSIX, though?
    – user529758
    Commented May 1, 2013 at 11:09
  • @H2CO3: yes, it's described by POSIX as in the link you provided.
    – pmg
    Commented May 1, 2013 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.