Linux命令basename,dirname

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.