The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Beating a dead basename(horse);

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
Beating a dead basename(horse); Posted: Aug 22, 2005 11:38 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Daniel Berger.
Original Post: Beating a dead basename(horse);
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
Ok, so I couldn't let it drop, mmkay? It turns out that the Solaris version of basename() is just as screwed up as the Linux version in that it's easy to get it to segfault on edge cases. In the interests of my sanity, I wrote my own version:
char* basename(char* str){
   int i = 0;
   char sep = '/';
   char* ptr = malloc(sizeof(str));

   /* Return string as-is if no separator is found */
   if(!strchr(str, sep))
      return str;

   strcpy(ptr, str);

   /* Get the count of trailing separators, if any */
   while(str[strlen(str)-(i+1)] == sep){ ++i; }

   /* Trim trailing separators */
   if(i){
      ptr[strlen(str)-i] = '\0';
      if(!strlen(ptr))
         strcpy(ptr, "/"); /* The base of root is root */
   }

   /* Get portion of string after last '/' character */
   if( (strchr(ptr, sep)) && (strlen(ptr) > 1) )
      ptr = (strrchr(ptr, sep) + 1);

   return ptr;
}

I would have run this through CUnit, but I couldn't get the darn thing to build. Anyway, here are some results I manually sent to stdout:
basename("foo")         # foo
basename("/foo")        # foo
basename("/foo/bar")    # bar
basename("/foo/bar.rb") # bar.rb

# Edge cases
basename("")        # ""
basename("/")       # /
basename("//")      # /
basename("/foo/")   # foo
basename('//foo//") # foo

I also have a version that accepts an optional argument, but it's too easy to make it segfault because variadic arguments in C, well, suck.

Read: Beating a dead basename(horse);

Topic: Oocli Fantasies Previous Topic   Next Topic Topic: Mac OS X’s green button?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use