aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorH. Peter Anvin <hpa@zytor.com>2018-09-17 23:06:28 -0700
committerH. Peter Anvin <hpa@zytor.com>2018-09-17 23:06:28 -0700
commit6e33dec2bdb86e09258544fcc7e5dc8398482945 (patch)
tree9e6e60cb9729a5db2c4889e264187e5a4a581cfa
parentd4ff712c9ebd974a9ea2229ac2856f3e03cacb13 (diff)
downloadabc80sim-6e33dec2bdb86e09258544fcc7e5dc8398482945.tar.gz
abc80sim-6e33dec2bdb86e09258544fcc7e5dc8398482945.tar.xz
abc80sim-6e33dec2bdb86e09258544fcc7e5dc8398482945.zip
tempfile: handle binary/text mode flag a *little* bit saner...
-rw-r--r--tempfile.c30
-rw-r--r--tempfile.h8
2 files changed, 29 insertions, 9 deletions
diff --git a/tempfile.c b/tempfile.c
index 42fbc7a..27088b0 100644
--- a/tempfile.c
+++ b/tempfile.c
@@ -6,9 +6,9 @@
#include "compiler.h"
#include "tempfile.h"
-#if 0 //def HAVE_MKSTEMP
+#ifdef HAVE_MKSTEMP
-FILE *temp_file(char **filenamep, const char *mode)
+FILE *temp_file(char **filenamep, enum temp_file_mode mode)
{
static const char template[] = "abc80_print_XXXXXX";
char *filename = NULL;
@@ -26,7 +26,7 @@ FILE *temp_file(char **filenamep, const char *mode)
if (fd < 0)
goto err;
- f = fdopen(fd, mode);
+ f = fdopen(fd, (mode == TF_BINARY) ? "w+b" : "w+t");
if (!f)
goto err;
@@ -59,13 +59,29 @@ err:
# define O_SHORT_LIVED 0
#endif
-FILE *temp_file(char **filenamep, const char *mode)
+#if defined(__WIN32__) && defined(_O_U16TEXT)
+# define UNICODE_O_FLAGS _O_U16TEXT
+#else
+# define UNICODE_O_FLAGS O_TEXT
+#endif
+
+FILE *temp_file(char **filenamep, enum temp_file_mode mode)
{
char *filename = NULL;
int err;
int fd = -1;
FILE *f = NULL;
int attempts = TMP_MAX;
+ int openflags;
+ static const int mode_openflags[] =
+ {
+ [TF_BINARY] = O_BINARY,
+ [TF_TEXT] = O_TEXT,
+ [TF_UNICODE] = UNICODE_O_FLAGS
+ };
+
+ openflags = O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_SHORT_LIVED;
+ openflags |= mode_openflags[mode];
*filenamep = NULL;
@@ -77,15 +93,13 @@ FILE *temp_file(char **filenamep, const char *mode)
if (!filename)
goto err;
- fd = open(filename,
- O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_BINARY|O_SHORT_LIVED,
- S_IREAD|S_IWRITE);
+ fd = open(filename, openflags, S_IREAD|S_IWRITE);
} while (fd < 0 && errno == EEXIST && --attempts);
if (fd < 0)
goto err;
- f = fdopen(fd, mode);
+ f = fdopen(fd, "w+");
if (!f)
goto err;
diff --git a/tempfile.h b/tempfile.h
index ed4e36e..43c4ea7 100644
--- a/tempfile.h
+++ b/tempfile.h
@@ -3,6 +3,12 @@
#include "compiler.h"
-extern FILE *temp_file(char **filename, const char *mode);
+enum temp_file_mode {
+ TF_BINARY, /* Raw binary */
+ TF_TEXT, /* Text mode compatible with ASCII */
+ TF_UNICODE /* Platform preferred Unicode encoding */
+};
+
+extern FILE *temp_file(char **filename, enum temp_file_mode mode);
#endif /* TEMPFILE_H */