posix_dirname.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // $Id$
  3. //
  4. #include<__vic/posix/fs.h>
  5. namespace __vic { namespace posix {
  6. //----------------------------------------------------------------------------
  7. void append_dirname(const std::string &path, std::string &res)
  8. {
  9. std::string::size_type len = path.length();
  10. switch(len)
  11. {
  12. case 0: res += '.'; return;
  13. case 1: res += *path.begin() == '/' ? '/' : '.'; return;
  14. }
  15. // Precondition: length() > 1
  16. // Ignore trailing '/'
  17. std::string::size_type pos = path.rfind('/',
  18. path[len - 1] == '/' ? len - 2 : std::string::npos);
  19. switch(pos)
  20. {
  21. case 0: res += '/'; return;
  22. case std::string::npos: res += '.'; return;
  23. }
  24. res.append(path, 0, pos);
  25. }
  26. //----------------------------------------------------------------------------
  27. std::string dirname(const std::string &path)
  28. {
  29. std::string res;
  30. append_dirname(path, res);
  31. return res;
  32. }
  33. //----------------------------------------------------------------------------
  34. void dirname(const std::string &path, std::string &res)
  35. {
  36. res.clear();
  37. append_dirname(path, res);
  38. }
  39. //----------------------------------------------------------------------------
  40. }} // namespace