Implement mkdtemp()
authorThomas Jarosch <thomas.jarosch@intra2net.com>
Thu, 8 Jul 2010 12:37:57 +0000 (14:37 +0200)
committerThomas Jarosch <thomas.jarosch@intra2net.com>
Thu, 22 Sep 2011 14:25:16 +0000 (16:25 +0200)
src/filefunc.cpp
src/filefunc.hxx
test/test_filefunc.cpp

index 6e10ccc..bfba003 100644 (file)
@@ -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<char> 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
index 795b3f2..d49fd47 100644 (file)
@@ -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
index 0dc1b3a..fb03723 100644 (file)
@@ -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()