basename.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. //
  11. // See also: dirname, pathinfo
  12. inline std::string basename(const std::string & path);
  13. }
  14. // Implementation
  15. #include <algorithm>
  16. inline std::string igl::basename(const std::string & path)
  17. {
  18. if(path == "")
  19. {
  20. return std::string("");
  21. }
  22. // http://stackoverflow.com/questions/5077693/dirnamephp-similar-function-in-c
  23. std::string::const_reverse_iterator last_slash =
  24. std::find(
  25. path.rbegin(),
  26. path.rend(), '/');
  27. if( last_slash == path.rend() )
  28. {
  29. // No slashes found
  30. return path;
  31. }else if(1 == (last_slash.base() - path.begin()))
  32. {
  33. // Slash is first char
  34. return std::string(path.begin()+1,path.end());
  35. }else if(path.end() == last_slash.base() )
  36. {
  37. // Slash is last char
  38. std::string redo = std::string(path.begin(),path.end()-1);
  39. return igl::basename(redo);
  40. }
  41. return std::string(last_slash.base(),path.end());
  42. }
  43. #endif