// basename_r.c // PUBLIC DOMAIN // http:///www.purposeful.co.uk/software/yabaplib /* I, Tom Vajzovic, am the author of this software and its documentation. I permanently abandon all intellectual property rights in them, including copyright, trademarks, design rights, database right, patents, and the right to be identified as the author. I am fairly certain that the software does what the documentation says it does, but I do not guarantee that it does, or that it does what you think it should. I do not guarantee that it will not have undesirable side effects. You are free to use, modify and distribute this software as you please, but you do so at your own risk. If you do not pass on this warning then you may be responsible for any problems encountered by those who obtain the software through you. */ #include /* malloc() */ #include /* memcpy() */ #include "basename_r.h" size_t dirname_len( const char *name ){ if( ! name ) return 0; { const char *next_slash= name; size_t len= 0; for( ;; ){ while( *next_slash && '/' != *next_slash ) ++next_slash; { const char *slashes= next_slash; while( '/' == *slashes ) ++slashes; if( !* slashes ) return len ? len : '/' == *name ? 1 : 0; else { len= next_slash - name; next_slash= slashes; } } } } } const char *dirname_r( char *name ){ size_t len= dirname_len( (const char*) name ); if( ! len ) return "."; name[ len ]= 0; return (const char*) name; } char *dirname_dup( const char *name ){ size_t len= dirname_len( name ); if( len ){ char *dup= malloc( len + 1 ); if( dup ){ memcpy( dup, name, len ); dup[ len ]= 0; } return dup; } else { char *dup= malloc( 2 ); if( dup ){ dup[0]= '.'; dup[1]= 0; } return dup; } } const char *basename_wlen( const char *name, size_t *len ){ if( ! name || !* name ){ if( len ) *len= 1; return "."; } while( '/' == name[0] ) if( name[1] ) ++name; else { if( len ) *len= 1; return name; } { const char *next_slash= name; for( ;; ){ while( *next_slash && '/' != *next_slash ) ++next_slash; if( len ) *len= next_slash - name; while( '/' == *next_slash ) ++ next_slash; if( *next_slash ) name= next_slash; else return name; } } } const char *basename_r( char *name ){ size_t len; const char *base= basename_wlen( (const char*) name, & len ); if( base[ len ] ) ((char*)base)[ len ]= 0; /* safe since the only string literal is "." */ return base; } char *basename_dup( const char *name ){ size_t len; const char *base= basename_wlen( name, & len ); char *dup= malloc( len + 1 ); if( dup ){ memcpy( dup, base, len ); dup[ len ]= 0; } return dup; }