C中的dirname():是手动错了吗?

前端之家收集整理的这篇文章主要介绍了C中的dirname():是手动错了吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在这里引用 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?

那么……有谁知道这里发生了什么?

解决方法

Trailing ‘/’ characters are not counted as part of the pathname.

因此“/ usr /”与“/ usr”相同,它可能表示目录/中具有名称(目录条目名称)usr的文件或目录.函数dirname返回路径的父目录. / usr的父目录是/.似乎完全一致.

猜你在找的C&C++相关文章