From 08903414e3546bc2c76bef73b2337ccf79886530 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Thu, 18 Jun 2015 14:41:44 +0200 Subject: Move path and filesystem from build2 to libbutl --- butl/path.cxx | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 butl/path.cxx (limited to 'butl/path.cxx') diff --git a/butl/path.cxx b/butl/path.cxx new file mode 100644 index 0000000..5d804a9 --- /dev/null +++ b/butl/path.cxx @@ -0,0 +1,109 @@ +// file : butl/path.cxx -*- C++ -*- +// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd +// license : MIT; see accompanying LICENSE file + +#include + +#ifdef _WIN32 +# include // _MAX_PATH +# include // _[w]getcwd, _[w]chdir +#else +# include // EINVAL +# include // mbstowcs, wcstombs +# include // PATH_MAX +# include // getcwd, chdir +#endif + +#include + +using namespace std; + +namespace butl +{ + char const* invalid_path_base:: + what () const throw () + { + return "invalid filesystem path"; + } + + // + // char + // + + template <> + path_traits::string_type path_traits:: + current () + { + // @@ throw system_error (and in the other current() versions). + +#ifdef _WIN32 + char cwd[_MAX_PATH]; + if(_getcwd(cwd, _MAX_PATH) == 0) + throw system_error (errno, system_category ()); +#else + char cwd[PATH_MAX]; + if (getcwd (cwd, PATH_MAX) == 0) + throw system_error (errno, system_category ()); +#endif + + return string_type (cwd); + } + + template <> + void path_traits:: + current (string_type const& s) + { +#ifdef _WIN32 + if(_chdir(s.c_str ()) != 0) + throw system_error (errno, system_category ()); +#else + if (chdir (s.c_str ()) != 0) + throw system_error (errno, system_category ()); +#endif + } + + // + // wchar_t + // + + template <> + path_traits::string_type path_traits:: + current () + { +#ifdef _WIN32 + wchar_t wcwd[_MAX_PATH]; + if(_wgetcwd(wcwd, _MAX_PATH) == 0) + throw system_error (errno, system_category ()); +#else + char cwd[PATH_MAX]; + if (getcwd (cwd, PATH_MAX) == 0) + throw system_error (errno, system_category ()); + + wchar_t wcwd[PATH_MAX]; + if (mbstowcs (wcwd, cwd, PATH_MAX) == size_type (-1)) + throw system_error (EINVAL, system_category ()); +#endif + + return string_type (wcwd); + } + + template <> + void path_traits:: + current (string_type const& s) + { +#ifdef _WIN32 + if(_wchdir(s.c_str ()) != 0) + throw system_error (errno, system_category ()); +#else + char ns[PATH_MAX + 1]; + + if (wcstombs (ns, s.c_str (), PATH_MAX) == size_type (-1)) + throw system_error (EINVAL, system_category ()); + + ns[PATH_MAX] = '\0'; + + if (chdir (ns) != 0) + throw system_error (errno, system_category ()); +#endif + } +} -- cgit v1.1