此函數是獲得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 }