How to extract filename from path

后端 未结 10 1916
遥遥无期
遥遥无期 2020-12-15 03:26

There should be something elegant in Linux API/POSIX to extract base file name from full path

10条回答
  •  盖世英雄少女心
    2020-12-15 03:50

    The basename() function returns the last component of a path, which could be a folder name and not a file name. There are two versions of the basename() function: the GNU version and the POSIX version.

    The GNU version can be found in string.h after you include #define _GNU_SOURCE:

        #define _GNU_SOURCE
    
        #include 
    

    The GNU version uses const and does not modify the argument.

        char * basename (const char *path)

    This function is overridden by the XPG (POSIX) version if libgen.h is included.

        char * basename (char *path)

    This function may modify the argument by removing trailing '/' bytes. The result may be different from the GNU version in this case:

        basename("foo/bar/")

    will return the string "bar" if you use the XPG version and an empty string if you use the GNU version.

    References:

      basename (3) - Linux Man Pages
      Function: char * basename (const char *filename), Finding Tokens in a String.

提交回复
热议问题