Decave
Decave

Reputation: 127

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.

Upvotes: 0

Views: 89

Answers (2)

pmg
pmg

Reputation: 108978

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");
}

Upvotes: 2

user529758
user529758

Reputation:

This is what the dirname() function is for:

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

Upvotes: 0

Related Questions