Fix bug #21280. Thanks to John Darrington for review.
[pspp-builds.git] / src / data / file-name.c
index f3b168176c0c63918d741ac9637fb9e81e8f6657..f8ad11d07a342f22fd5bf4cfa026d9a93a412ce0 100644 (file)
 
 #include <ctype.h>
 #include <errno.h>
+#include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <unistd.h>
 
 #include "intprops.h"
 #include "minmax.h"
@@ -320,6 +322,30 @@ fn_close (const char *fn, FILE *f)
     return fclose (f);
 }
 
+/* Creates a new file named FN with the given PERMISSIONS bits,
+   and returns a stream for it or a null pointer on failure.
+   MODE should be "w" or "wb". */
+FILE *
+create_stream (const char *fn, const char *mode, mode_t permissions)
+{
+  int fd;
+  FILE *stream;
+
+  fd = open (fn, O_WRONLY | O_CREAT | O_TRUNC, permissions);
+  if (fd < 0)
+    return NULL;
+
+  stream = fdopen (fd, mode);
+  if (stream == NULL)
+    {
+      int save_errno = errno;
+      close (fd);
+      errno = save_errno;
+    }
+
+  return stream;
+}
+
 #if !(defined _WIN32 || defined __WIN32__)
 /* A file's identity. */
 struct file_identity