Added locally_change_current_dir

This commit is contained in:
Davis King 2014-04-26 15:35:45 -04:00
parent 4934b0020f
commit 672b4b27d8
3 changed files with 82 additions and 0 deletions

View File

@ -14,5 +14,7 @@
#include "misc_api/posix.h"
#endif
#include "misc_api/misc_api_shared.h"
#endif // DLIB_MISC_APi_

View File

@ -59,6 +59,41 @@ namespace dlib
to change the current working directory.
!*/
// ----------------------------------------------------------------------------------------
class locally_change_current_dir : noncopyable
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is a RAII tool for safely switching the current directory
to a new directory and then automatically switching back to the original
directory upon this object's destruction.
!*/
public:
explicit locally_change_current_dir (
const std::string& new_dir
);
/*!
ensures
- calls set_current_dir(new_dir)
- #old_dir() == The value of get_current_dir() prior to switching to new_dir.
!*/
const std::string& old_dir (
) const;
/*!
ensures
- returns the directory we switch back to once this object is destructed.
!*/
~locally_change_current_dir(
);
/*!
ensures
- calls set_current_dir(old_dir())
!*/
};
// ----------------------------------------------------------------------------------------
class dir_create_error : public error {

View File

@ -0,0 +1,45 @@
// Copyright (C) 2014 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_MISC_API_ShARED_H__
#define DLIB_MISC_API_ShARED_H__
#include <string>
#include "../noncopyable.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class locally_change_current_dir : noncopyable
{
public:
explicit locally_change_current_dir (
const std::string& new_dir
)
{
_old_dir = get_current_dir();
set_current_dir(new_dir);
}
~locally_change_current_dir()
{
set_current_dir(_old_dir);
}
const std::string& old_dir (
) const
{
return _old_dir;
}
private:
std::string _old_dir;
};
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_MISC_API_ShARED_H__