convert a fully qualified path to relative path

convert a fully qualified path to relative path

Download torelativepath.zip

Synopsis:

torelativepath.cpp


torelativepath.cpp

Synopsis
#include <string>
#include <algorithm>
using namespace std;

#include "utx.h"

//defined in other snippets
extern string toDosPath(const string& path);
extern string toLowerCase(const string& s);

string torelativepath(const string& path, const string& prefix)
  {
  string fqpath = toLowerCase(toDosPath(path));
  string root = toLowerCase(toDosPath(prefix));

  if (fqpath.find(root) == string::npos)
    throw exception("path does not start with given prefix");
  if (root.length() == fqpath.length()) return "";
  return path.substr(prefix.length() + (fqpath[root.length()] == '\\' ? 1 : 0));
  }

//--- Tests
TEST(emptycases)
  {
  utxassert(torelativepath("", ""), "");
  utxassert(torelativepath("c:\\", "c:\\"), "");
  }
  TEST(normal)
  {
    utxassert(torelativepath("c:\\abc", "c:\\"), "abc");
    utxassert(torelativepath("c:\\abc\\def", "c:\\abc"), "def");
    utxassert(torelativepath("c:\\abc\\def", "c:\\"), "abc\\def");
    utxassert(torelativepath("c:\\abc\\def", "c:"), "abc\\def");
  }
  TEST(ignorecaseinprefix)
  {
    utxassert(torelativepath("c:\\abc", "c:\\"), "abc");
    utxassert(torelativepath("c:\\abc", "C:\\"), "abc");
    utxassert(torelativepath("C:\\abc", "c:\\"), "abc");
    utxassert(torelativepath("C:\\abc", "C:\\"), "abc");
    utxassert(torelativepath("c:\\aBc\\def", "c:\\abC"), "def");
  }
  TEST(preservecaseinpath)
  {
    utxassert(torelativepath("c:\\Abc", "c:\\"), "Abc");
  }
TEST(notaprefix)
  {
  try
    {
    utxassert(torelativepath("c:\\abc\\def", "c:\\xyz"), "def");
    utxBoolAssert(false);
    } 
  catch(exception /*ex*/)
    {
    utxBoolAssert(true);
    }
  }






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001,2002,2003,2004,2005,2006,2007