dirname, basename - analysis path member

Overview (SYNOPSIS)

#include <libgen.h>

char *dirname(char *path);
char *basename(char *path);

 

Description (DESCRIPTION)

dirname and basename to the path name of a null-terminated decomposition of directory and file names. In general, dirname return to the previous partial path name, up to (but not including) the last '/', and basename last return '/' behind the content. If the path name ends with '/', the '/' are not considered part of the pathname.

 

If the path name of the path does not contain a slash '/', dirname returns the string ".", And basename return path replicas. If the path name of the path is "/", the dirname and basename are returned "/". If the path name path or is a NULL pointer points to an empty string, the dirname and basename are returned. "."

The dirname returned string "/", and basename string concatenated with the return, it is capable of generating a complete path name.

Whether dirname or basename are likely to change the path of content, so if you need to protect the existing path name, shall transmit a copy as a parameter. In addition, dirname and basename return pointers may point to a static memory allocation, it will be covered by the next call.

The following example (taken from SUSv2) shows the different path names, dirname and basename string returned:

 

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

 

Example (EXAMPLE)

char *dirc, *basec, *bname, *dname;
char *path = "/etc/passwd";

dirc = strdup(path);
basec = strdup(path);
dname = dirname(dirc);
bname = basename(basec);
printf("dirname=%s, basename=%s\n", dname, bname);
free(dirc);
free(basec);

 

Return value (RETURN VALUE)

dirname and basename both return the pointer to a null-terminated string. 

Guess you like

Origin www.cnblogs.com/fanweisheng/p/11080798.html