0

Hi guys,

I'm writing a simple function to return the file portion of a path. Strangely, the results I'm trying to duplicate accept something like a/b/c\d\e\file as a valid path, so I'm really just searching for the last occurrence of a slash or backslash.

Anyhow, I'm curious what your thoughts are about the implementation-dependent overflow below:

string GetFile( const string& strFile )
{
	assert( string::npos + 1 == 0 );

	// begin at the first character after the last slash or backslash found
	size_t posSlash = strFile.rfind( '/' ) + 1;
	size_t posBackSlash = strFile.rfind( '\\' ) + 1;

	// look at the last slash or backslash -- whichever is greater
	size_t posSubstring = ( posSlash > posBackSlash ) ? posSlash : posBackSlash;

	return strFile.substr( posSubstring );
}

Thanks!

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Galf
0

>> so I'm really just searching for the last occurrence of a slash or backslash.

Have you considered string::find_last_of()?

I had actually re-written it to use find_last_of immediately after posting :-). That said, the overflow question is still there.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.