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!

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

Have you considered string::find_last_of()?

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.