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.
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: