Dirname () in C: wrong manual?

Quoting guide here:

The dirname () and basename () functions interrupt the null termination of pathname into the directory and file names. In the usual case, dirname () returns the string before, but not including the final '/' , and basename () returns the component after the final '/'. Forced "/" characters are not considered part of the path.

And later you have this little table:

path dirname basename "/usr/lib" "/usr" "lib" "/usr/" "/" "usr" // wat? "usr" "." "usr" "/" "/" "/" "." "." "." ".." "." ".." 

Why dirname( "/usr/") return "/" rather than "/usr" ?
The suggestion in the manual tells me that I should get /usr as a result.
I tested the actual result in a dummy program, and it behaves the same as in the manual.

 #include <libgen.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char const *argv[]) { const char *mydir="/usr/"; char *dummy = strdup( mydir ); char *dummy2 = strdup( mydir ); char *dname = dirname( dummy ); char *bname = basename( dummy2 ); printf("mydir: '%s', dname: '%s', bname: '%s'\n", mydir, dname, bname); free( dummy ); free( dummy2 ); return 0; } $ ./test mydir: '/usr/', dname: '/', bname: 'usr' 

Now, I would expect:

 path dirname basename "/usr/" "/usr" "" // more consistent? 

So, does anyone understand what is going on here?

+6
source share
2 answers

Trailing '/' characters are not considered part of the path.

Therefore, "/ usr /" matches "/ usr", which can indicate a file or directory with the name (directory entry with the name) usr in the / directory. The dirname function returns the parent directory of the path. Parent directory /usr - / . It seems quite consistent.

+14
source

The directory is also a file. usr , of course, is the base name of the /usr file. This follows the manual exactly - in /usr , root- / is final / and usr , which follows, therefore, is basic.

Regarding /usr/ v. /usr , I suspect that this is due to the fact that the final / always swallowed, and this is indicated somewhere else or falls under the qualification β€œin the usual case”. Or else /usr/// and /usr/////////// will refer to completely different objects ...

+4
source

All Articles