Linux Command basename, dirname

Source: Internet
Author: User

This function is used to obtain the basename in directory, for example, basename ("android/system/core "),

The returned result is "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);/* allocate memory space */
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 "."*/
41 if (Path = NULL | * Path = '\ 0 '){
/* Judge not to be blank */
42 startp = ".";
43 Len = 1;
44 goto exit;
45}
46
47/* strip trailing slashes */
48 endp = path + strlen (PATH)-1;/* If the last bit of directory is '/', remove it */
49 while (endp> Path & * endp = '/')
50 endp --;
51
52/* All slashes becomes "/" * // * all directories are '/'*/
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 )! = '/')/* Starts from the last (rightmost) bit of directory not '/'. It goes to the left and ends with a slash"
62 startp --;
63
64 Len = endp-startp + 1;/basename length/
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);/* save basename to buffer */
79 buffer [Len] = 0;
80}
81 return result;
82}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.