posix_basename.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. //
  2. // $Id$
  3. //
  4. #include<__vic/posix/fs.h>
  5. namespace __vic { namespace posix {
  6. //----------------------------------------------------------------------------
  7. void append_basename(const std::string &path, std::string &res)
  8. {
  9. std::string::const_iterator end = path.end();
  10. // Skip all trailing slashes
  11. while(end > path.begin() + 1 && *(end - 1) == '/') end--;
  12. if(end == path.begin() + 1 && *path.begin() == '/')
  13. { res += '/'; return; } // only one '/'
  14. std::string::size_type pos = path.rfind('/', end - path.begin() - 1);
  15. if(pos == std::string::npos)
  16. res.append(path, 0, end - path.begin());
  17. else
  18. res.append(path, pos + 1, end - (path.begin() + pos + 1));
  19. }
  20. //----------------------------------------------------------------------------
  21. std::string basename(const std::string &path)
  22. {
  23. std::string res;
  24. append_basename(path, res);
  25. return res;
  26. }
  27. //----------------------------------------------------------------------------
  28. void basename(const std::string &path, std::string &res)
  29. {
  30. res.clear();
  31. append_basename(path, res);
  32. }
  33. //----------------------------------------------------------------------------
  34. }} // namespace