summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--include/libfile.h2
-rw-r--r--lib/libfile.c27
2 files changed, 29 insertions, 0 deletions
diff --git a/include/libfile.h b/include/libfile.h
index dd0b00f988..6dbb81a241 100644
--- a/include/libfile.h
+++ b/include/libfile.h
@@ -26,4 +26,6 @@ int make_directory(const char *pathname);
int unlink_recursive(const char *path, char **failedpath);
+char *make_temp(const char *template);
+
#endif /* __LIBFILE_H */
diff --git a/lib/libfile.c b/lib/libfile.c
index 6b70306dbd..79054eb5ac 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -20,6 +20,7 @@
#include <malloc.h>
#include <libfile.h>
#include <progress.h>
+#include <stdlib.h>
#include <linux/stat.h>
/*
@@ -485,3 +486,29 @@ int open_and_lseek(const char *filename, int mode, loff_t pos)
return fd;
}
+
+/**
+ * make_temp - create a name for a temporary file
+ * @template: The filename prefix
+ *
+ * This function creates a name for a temporary file. @template is used as a
+ * template for the name which gets appended a 8-digit hexadecimal number to
+ * create a unique filename.
+ *
+ * Return: This function returns a filename which can be used as a temporary
+ * file lateron. The returned filename must be freed by the caller.
+ */
+char *make_temp(const char *template)
+{
+ char *name = NULL;
+ struct stat s;
+ int ret;
+
+ do {
+ free(name);
+ name = basprintf("/tmp/%s-%08x", template, random32());
+ ret = stat(name, &s);
+ } while (!ret);
+
+ return name;
+}