[vlc-devel] [PATCH v3 8/14] core: add vlc_MakeTmpFile() helper

Lyndon Brown jnqnfe at gmail.com
Wed Oct 14 04:54:46 CEST 2020


From: Lyndon Brown <jnqnfe at gmail.com>
Date: Tue, 6 Oct 2020 01:08:32 +0100
Subject: core: add vlc_MakeTmpFile() helper

to reduce messy and duplicated code creating temporary files with
config_GetTempPath() and vlc_mkstemp().

created as an inline function since there will be so few users.

diff --git a/include/vlc_fs.h b/include/vlc_fs.h
index e6cee45fd1..46536f9ac5 100644
--- a/include/vlc_fs.h
+++ b/include/vlc_fs.h
@@ -45,6 +45,7 @@ struct iovec;
 # define lseek lseek64
 #endif
 
+#include <vlc_configuration.h> /* config_GetTempPath() */
 
 /**
  * \defgroup os Operating system
@@ -116,6 +117,37 @@ VLC_API int vlc_openat(int fd, const char *filename, int flags, ...) VLC_USED;
  */
 VLC_API int vlc_mkstemp( char * );
 
+/**
+ * Temporary file creation helper
+ *
+ * Creates a unique temporary file, using config_GetTempPath() to determine the
+ * directory in which to create it, and using vlc_mkstemp() for the creation.
+ *
+ * Note, the returned `path` pointer must be free'd with free(), except when
+ * the returned file descriptor is -1 indicating error, where is it undefined.
+ *
+ * @param path [OUT] full path of the created file.
+ * @param prefix filename prefix, to which 'XXXXXX' will be appended for mkstemp.
+ * @return file descriptor, or -1 on error.
+ */
+static inline int vlc_MakeTmpFile( char **path, const char *prefix )
+{
+    char *tmpdir = config_GetTempPath();
+    if (tmpdir == NULL)
+        return -1;
+
+    if (asprintf(path, "%s" DIR_SEP "%sXXXXXX", tmpdir, prefix) < 0) {
+        free(tmpdir);
+        return -1;
+    }
+    free(tmpdir);
+
+    int fd = vlc_mkstemp(*path);
+    if (fd == -1)
+        free(*path);
+    return fd;
+}
+
 /**
  * Duplicates a file descriptor. The new file descriptor has the close-on-exec
  * descriptor flag preset.



More information about the vlc-devel mailing list