librostlab
1.0.20
|
00001 /* 00002 Copyright (C) 2011 Laszlo Kajan, Technical University of Munich, Germany 00003 00004 This file is part of librostlab. 00005 00006 librostlab is free software: you can redistribute it and/or modify 00007 it under the terms of the GNU Lesser General Public License as published by 00008 the Free Software Foundation, either version 3 of the License, or 00009 (at your option) any later version. 00010 00011 This program is distributed in the hope that it will be useful, 00012 but WITHOUT ANY WARRANTY; without even the implied warranty of 00013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00014 GNU Lesser General Public License for more details. 00015 00016 You should have received a copy of the GNU Lesser General Public License 00017 along with this program. If not, see <http://www.gnu.org/licenses/>. 00018 */ 00019 #ifndef ROSTLAB_CWD_RESOURCE 00020 #define ROSTLAB_CWD_RESOURCE 00021 00022 #include <errno.h> 00023 #include <stdexcept> 00024 #include <unistd.h> 00025 #include <string.h> 00026 00027 namespace rostlab { 00028 00029 class cwd_resource 00030 { 00031 private: 00032 string _olddir; 00033 // this is a resource - disable copy contructor and copy assignment 00034 cwd_resource( const cwd_resource& ){}; 00035 cwd_resource& 00036 operator=(const cwd_resource&){return *this;}; 00037 public: 00038 cwd_resource() : _olddir("") {}; 00039 00040 cwd_resource( const string& __dirname ) : _olddir("") 00041 { 00042 acquire( __dirname ); 00043 } 00044 00045 inline void acquire( const string& __dirname ) throw (runtime_error) 00046 { 00047 release(); 00048 // 00049 char *buf = NULL; 00050 if( ( buf = getcwd( NULL, 0 ) ) == NULL ) throw runtime_error( string("failed to get working directory: ") + strerror( errno ) ); 00051 string cwd = buf; free( buf ); buf = NULL; 00052 00053 if( chdir( __dirname.c_str() ) ) throw runtime_error( "failed to chdir to '" + __dirname + "': " + strerror( errno ) ); 00054 _olddir = cwd; 00055 } 00056 00057 inline void release() throw (runtime_error) 00058 { 00059 if( _olddir != "" ) 00060 { 00061 if( chdir( _olddir.c_str() ) ) throw runtime_error( "failed to chdir to '" + _olddir + "': " + strerror( errno ) ); 00062 _olddir = ""; 00063 } 00064 } 00065 00066 virtual ~cwd_resource() 00067 { 00068 release(); 00069 } 00070 }; 00071 00072 }; 00073 00074 #endif // ROSTLAB_CWD_RESOURCE 00075 // vim:et:ts=2:ai: