librostlab  1.0.20
cwd_resource.h
Go to the documentation of this file.
1 /*
2  Copyright (C) 2011 Laszlo Kajan, Technical University of Munich, Germany
3 
4  This file is part of librostlab.
5 
6  librostlab is free software: you can redistribute it and/or modify
7  it under the terms of the GNU Lesser General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  This program is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU Lesser General Public License for more details.
15 
16  You should have received a copy of the GNU Lesser General Public License
17  along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 #ifndef ROSTLAB_CWD_RESOURCE
20 #define ROSTLAB_CWD_RESOURCE
21 
22 #include <errno.h>
23 #include <stdexcept>
24 #include <unistd.h>
25 #include <string.h>
26 
27 namespace rostlab {
28 
30 {
31  private:
32  string _olddir;
33  // this is a resource - disable copy contructor and copy assignment
34  cwd_resource( const cwd_resource& ){};
36  operator=(const cwd_resource&){return *this;};
37  public:
38  cwd_resource() : _olddir("") {};
39 
40  cwd_resource( const string& __dirname ) : _olddir("")
41  {
42  acquire( __dirname );
43  }
44 
45  inline void acquire( const string& __dirname ) throw (runtime_error)
46  {
47  release();
48  //
49  char *buf = NULL;
50  if( ( buf = getcwd( NULL, 0 ) ) == NULL ) throw runtime_error( string("failed to get working directory: ") + strerror( errno ) );
51  string cwd = buf; free( buf ); buf = NULL;
52 
53  if( chdir( __dirname.c_str() ) ) throw runtime_error( "failed to chdir to '" + __dirname + "': " + strerror( errno ) );
54  _olddir = cwd;
55  }
56 
57  inline void release() throw (runtime_error)
58  {
59  if( _olddir != "" )
60  {
61  if( chdir( _olddir.c_str() ) ) throw runtime_error( "failed to chdir to '" + _olddir + "': " + strerror( errno ) );
62  _olddir = "";
63  }
64  }
65 
66  virtual ~cwd_resource()
67  {
68  release();
69  }
70 };
71 
72 };
73 
74 #endif // ROSTLAB_CWD_RESOURCE
75 // vim:et:ts=2:ai:
void acquire(const string &__dirname)
Definition: cwd_resource.h:45
cwd_resource(const string &__dirname)
Definition: cwd_resource.h:40