dirname.h 1.1 KB

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