Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) GetExtension

 

std::string code snippet to get a filename's extension.

 

Thanks goes to Curtis Krauskopf, who supported me to improve the (terrible and error-prone) code of GetExtension.

 

 

#include <string>
#include <cassert>

//Returns the extension of a filename
//Assumes that the filename has an extension
//From http://www.richelbilderbeek.nl/CppGetExtension.htm
const std::string GetExtension(const std::string& filename)
{
  const std::size_t i = filename.rfind('.');
  assert(i != std::string::npos && "Filename must contain a dot");
  assert(i != filename.size() - 1 && "Filename must not end with a dot");
  assert(filename[i+1] != '\\' && "Filename must have an extension");
  assert(filename[i+1] != '/' && "Filename must have an extension");
  return filename.substr(i+1,filename.size());
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict