From f03a8892744d9bf15d9fcfbe1dfa7af4be56f2bd Mon Sep 17 00:00:00 2001 From: Glenn Maynard Date: Wed, 29 Oct 2003 20:18:04 +0000 Subject: [PATCH] add Dirname, optimize Basename --- stepmania/src/RageUtil.cpp | 44 ++++++++++++++++++++++++++++++++------ stepmania/src/RageUtil.h | 4 ++-- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/stepmania/src/RageUtil.cpp b/stepmania/src/RageUtil.cpp index ee08f8c254..a154f1add4 100644 --- a/stepmania/src/RageUtil.cpp +++ b/stepmania/src/RageUtil.cpp @@ -957,15 +957,47 @@ CString WcharDisplayText(wchar_t c) * a/b/c -> c * a/b/c/ -> c */ -CString Basename(CString dir) +CString Basename( const CString &dir ) { - TrimRight(dir, "/\\"); + unsigned end = dir.find_last_not_of( "/\\" ); + if( end == dir.npos ) + return ""; - unsigned pos = dir.find_last_of("/\\"); - if(pos != dir.npos) - return dir.substr(pos+1); + unsigned start = dir.find_last_of( "/\\", end ); + if( start == dir.npos ) + start = 0; + else + ++start; - return dir; + return dir.substr( start, end-start+1 ); +} + +/* Return all but the last named component of dir: + * a/b/c -> a/b/ + * a/b/c/ -> a/b/ + * c/ -> ./ + * /foo -> / + * / -> / + */ +CString Dirname( const CString &dir ) +{ + /* Special case: "/" -> "/". */ + if( dir.size() == 1 && dir[0] == SLASH[0] ) + return SLASH; + + int pos = dir.size()-1; + /* Skip trailing slashes. */ + while( pos >= 0 && dir[pos] == SLASH[0] ) + --pos; + + /* Skip the last component. */ + while( pos >= 0 && dir[pos] != SLASH[0] ) + --pos; + + if( pos < 0 ) + return "." SLASH; + + return dir.substr(0, pos+1); } CString Capitalize( CString s ) diff --git a/stepmania/src/RageUtil.h b/stepmania/src/RageUtil.h index 37b3f4f212..624f444d68 100644 --- a/stepmania/src/RageUtil.h +++ b/stepmania/src/RageUtil.h @@ -231,8 +231,8 @@ void Replace_Unicode_Markers( CString &Text ); void ReplaceText( CString &Text, const map &m ); CString WcharDisplayText(wchar_t c); -CString Basename(CString dir); - +CString Basename( const CString &dir ); +CString Dirname( const CString &dir ); CString Capitalize( CString s ); #ifndef WIN32