Search code examples
cdirectory-structure

Obtain directory of a file in C code


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.


Solution

  • This is what the dirname() function is for:

    char path[] = "/var/www/index.html";
    char *dirn = dirname(path);
    printf("Dirname: %s\n", dirn);