util: add os_file_create_unique()
authorEric Engestrom <eric.engestrom@intel.com>
Mon, 3 Jun 2019 16:51:37 +0000 (17:51 +0100)
committerEric Engestrom <eric.engestrom@intel.com>
Fri, 28 Jun 2019 22:37:49 +0000 (23:37 +0100)
Signed-off-by: Eric Engestrom <eric.engestrom@intel.com>
Reviewed-by: Kristian H. Kristensen <hoegsberg@google.com>
Reviewed-by: Marek Olšák <marek.olsak@amd.com>
src/util/os_file.c
src/util/os_file.h

index 756164c..ae41506 100644 (file)
@@ -6,7 +6,30 @@
 #include "os_file.h"
 
 #include <errno.h>
+#include <fcntl.h>
 #include <stdlib.h>
+#include <sys/stat.h>
+
+
+#if defined(WIN32)
+#include <io.h>
+#define open _open
+#define fdopen _fdopen
+#define O_CREAT _O_CREAT
+#define O_EXCL _O_EXCL
+#define O_WRONLY _O_WRONLY
+#endif
+
+
+FILE *
+os_file_create_unique(const char *filename, int filemode)
+{
+   int fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, filemode);
+   if (fd == -1)
+      return NULL;
+   return fdopen(fd, "w");
+}
+
 
 #if defined(__linux__)
 
index 2f97c19..d691302 100644 (file)
@@ -8,11 +8,22 @@
 #ifndef _OS_FILE_H_
 #define _OS_FILE_H_
 
+#include <stdio.h>
+
 #ifdef  __cplusplus
 extern "C" {
 #endif
 
 /*
+ * Create a new file and opens it for writing-only.
+ * If the given filename already exists, nothing is done and NULL is returned.
+ * `errno` gets set to the failure reason; if that is not EEXIST, the caller
+ * might want to do something other than trying again.
+ */
+FILE *
+os_file_create_unique(const char *filename, int filemode);
+
+/*
  * Read a file.
  * Returns a char* that the caller must free(), or NULL and sets errno.
  */