basename.h 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #ifndef IGL_BASENAME_H
  2. #define IGL_BASENAME_H
  3. #include <string>
  4. namespace igl
  5. {
  6. // Function like PHP's basename
  7. // Input:
  8. // path string containing input path
  9. // Returns string containing basename (see php's basename)
  10. std::string basename(const std::string & path);
  11. }
  12. // Implementation
  13. #include <algorithm>
  14. std::string igl::basename(const std::string & path)
  15. {
  16. if(path == "")
  17. {
  18. return std::string("");
  19. }
  20. // http://stackoverflow.com/questions/5077693/dirnamephp-similar-function-in-c
  21. std::string::const_reverse_iterator last_slash =
  22. std::find(
  23. path.rbegin(),
  24. path.rend(), '/');
  25. if( last_slash == path.rend() )
  26. {
  27. // No slashes found
  28. return path;
  29. }else if(1 == (last_slash.base() - path.begin()))
  30. {
  31. // Slash is first char
  32. return std::string(path.begin()+1,path.end());
  33. }else if(path.end() == last_slash.base() )
  34. {
  35. // Slash is last char
  36. std::string redo = std::string(path.begin(),path.end()-1);
  37. return igl::basename(redo);
  38. }
  39. return std::string(last_slash.base(),path.end());
  40. }
  41. #endif