在这里引用
the manual:
The functions dirname() and basename() break a null-terminated
pathname string into directory and filename components. In the usual
case,dirname() returns the string up to,but not including,the final
‘/’,and basename() returns the component following the final ‘/’.
Trailing ‘/’ characters are not counted as part of the pathname.
后来,你有这个小桌子:
path dirname basename "/usr/lib" "/usr" "lib" "/usr/" "/" "usr" // wat? "usr" "." "usr" "/" "/" "/" "." "." "." ".." "." ".."
为什么dirname(“/ usr /”)返回“/”而不是“/ usr”?
手册中的句子告诉我应该得到/ usr作为结果.
我在虚拟程序中测试了实际结果,它的行为就像手册所说的那样.
#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'
现在,我期望的是:
path dirname basename "/usr/" "/usr" "" // more consistent?
那么……有谁知道这里发生了什么?