dirname.h 1.1 KB

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