From faf8475baca8392338e40b0d9c8e6574266a7722 Mon Sep 17 00:00:00 2001 From: Thomas Jarosch Date: Thu, 8 Jul 2010 14:37:57 +0200 Subject: [PATCH] Implement mkdtemp() --- src/filefunc.cpp | 20 ++++++++++++++++++++ src/filefunc.hxx | 2 ++ test/test_filefunc.cpp | 20 ++++++++++++++++++++ 3 files changed, 42 insertions(+), 0 deletions(-) diff --git a/src/filefunc.cpp b/src/filefunc.cpp index 6e10ccc..bfba003 100644 --- a/src/filefunc.cpp +++ b/src/filefunc.cpp @@ -751,4 +751,24 @@ bool recursive_delete(const std::string &path, std::string *error) return rtn; } // eo recursive_delete(const std::string&,std::string*) +/** + Create a unique temporary directory from path_template. + @param Path template. The last six characters must be XXXXXX. + @return Name of new directory or empty string on error. +*/ +std::string mkdtemp(const std::string &path_template) +{ + boost::scoped_array buf( new char[path_template.size()+1] ); + path_template.copy(buf.get(), path_template.size()); + buf[path_template.size()]=0; + + char *unique_dir = ::mkdtemp(buf.get()); + if (!unique_dir) + return ""; + + // Scoped pointer is still valid + return std::string(unique_dir); +} + + } // eo namespace I2n diff --git a/src/filefunc.hxx b/src/filefunc.hxx index 795b3f2..d49fd47 100644 --- a/src/filefunc.hxx +++ b/src/filefunc.hxx @@ -177,6 +177,8 @@ bool chown(const std::string& path, const I2n::User& user, const I2n::Group& gro bool recursive_delete(const std::string &path, std::string *error=NULL); +std::string mkdtemp(const std::string &path_template); + } #endif diff --git a/test/test_filefunc.cpp b/test/test_filefunc.cpp index 0dc1b3a..fb03723 100644 --- a/test/test_filefunc.cpp +++ b/test/test_filefunc.cpp @@ -344,4 +344,24 @@ BOOST_AUTO_TEST_CASE(TestCopyFileOk) BOOST_CHECK_EQUAL( false, size_is_zero ); } +BOOST_AUTO_TEST_CASE(TestMkdtemp) +{ + // Create unique directory + string unique_dir = I2n::mkdtemp("foobar.XXXXXX"); + BOOST_REQUIRE(unique_dir.size() > 0); + + // Test if it's really a directory + BOOST_CHECK_EQUAL(true, Stat(unique_dir).is_directory()); + + // Unlink it + BOOST_CHECK_EQUAL(true, I2n::recursive_delete(unique_dir)); +} + +BOOST_AUTO_TEST_CASE(TestMkdtempBrokenTemplate) +{ + // Broken directory template -> fail + string unique_dir = I2n::mkdtemp("foobar.XXX"); + BOOST_CHECK_EQUAL("", unique_dir); +} + BOOST_AUTO_TEST_SUITE_END() -- 1.7.1