此函数是获得directory中的basename, 比如basename(“android/system/core"),
返回的是"core"
37 basename(const char* path)
38 {39 static char* bname = NULL;
40 int ret;
41
42 if (bname == NULL) {
43 bname = (char *)malloc(MAXPATHLEN); /* 分配内存空间 */
44 if (bname == NULL)
45 return(NULL);
46 }
47 ret = basename_r(path, bname, MAXPATHLEN);
48 return (ret < 0) ? NULL : bname;
49 }
33 int
34 basename_r(const char* path, char* buffer, size_t bufflen)
35 {
36 const char *endp, *startp;
37 int len, result;
38 char temp[2];
39
40 /* Empty or NULL string gets treated as "." */
41 if (path == NULL || *path == '\0') { /* 判断不为空 */
42 startp = ".";
43 len = 1;
44 goto Exit;
45 }
46
47 /* Strip trailing slashes */
48 endp = path + strlen(path) - 1; /* 如果directory最后一位是'/' , 则把它去掉 */
49 while (endp > path && *endp == '/')
50 endp--;
51
52 /* All slashes becomes "/" */ /* directory 全部为'/' */
53 if (endp == path && *endp == '/') {
54 startp = "/";
55 len = 1;
56 goto Exit;
57 }
58
59 /* Find the start of the base */
60 startp = endp;
61 while (startp > path && *(startp - 1) != '/') /* 从directory最后一个(最右边)不为'/' 的位开始,往左数,数到遇到一个'/' 为止”
62 startp--;
63
64 len = endp - startp +1; /basename 的长度/
65
66 Exit:
67 result = len;
68 if (buffer == NULL) {
69 return result;
70 }
71 if (len > (int)bufflen-1) {
72 len = (int)bufflen-1;
73 result = -1;
74 errno = ERANGE;
75 }
76
77 if (len >= 0) {
78 memcpy( buffer, startp, len ); /* 将basename保存到buffer */中
79 buffer[len] = 0;
80 }
81 return result;
82 }