libmoost
/home/mhx/git/github/libmoost/include/moost/io/tempdir.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00028 #ifndef MOOST_IO_TEMPDIR_HPP
00029 #define MOOST_IO_TEMPDIR_HPP
00030 
00031 #include <cstdlib>
00032 #include <string>
00033 #include <vector>
00034 #include <stdexcept>
00035 #include <boost/filesystem.hpp>
00036 
00050 namespace moost { namespace io {
00051 
00052    class tempdir : public boost::filesystem::path
00053    {
00054       private:
00055          static std::string mktempdir(std::string const & pattern)
00056          {
00057             std::vector<char> buf(pattern.begin(), pattern.end());
00058             buf.push_back('\0'); // null terminate - thanks sven :)
00059 
00060             char const * path = mkdtemp(&buf[0]);
00061 
00062             if (!path)
00063             {
00064                throw std::runtime_error("unable to create tempdir");
00065             }
00066 
00067             return std::string(path);
00068 
00069          }
00070       public:
00071          tempdir(std::string pattern = "lastfm_moost_io_tempdir_XXXXXX")
00072             : boost::filesystem::path(mktempdir(pattern))
00073          {
00074          }
00075 
00076          ~tempdir()
00077          {
00078             // wave goodbye to your temporary directory
00079             boost::filesystem::remove_all(this->string());
00080          }
00081    };
00082 }}
00083 
00084 #endif