From 2e7bcb3205d95de79e12c5f939394280a7238feb Mon Sep 17 00:00:00 2001 From: Ulya Trofimovich Date: Tue, 5 Mar 2019 22:09:08 +0000 Subject: [PATCH] Use autoconf header detection to guard non-C++98 includes (POSIX file API). --- re2c/configure.ac | 8 ++++++- re2c/src/util/temp_file.cc | 48 +++++++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/re2c/configure.ac b/re2c/configure.ac index 3cb2b808..3152a0a8 100644 --- a/re2c/configure.ac +++ b/re2c/configure.ac @@ -97,7 +97,13 @@ TRY_CXXFLAG([-Weverything], m4_join([ ], # needed by src/c99_stdint.h # avoid AC_INCLUDES_DEFAULT -AC_CHECK_HEADERS([stdint.h], [], [], [[]]) +AC_CHECK_HEADERS([stdint.h], [], [], [[]]) +# needed for POSIX file API +AC_CHECK_HEADERS([sys/types.h], [], [], [[]]) +AC_CHECK_HEADERS([sys/stat.h], [], [], [[]]) +AC_CHECK_HEADERS([fcntl.h], [], [], [[]]) +AC_CHECK_HEADERS([unistd.h], [], [], [[]]) +AC_CHECK_HEADERS([io.h], [], [], [[]]) # windows POSIX-like API # list of possible types to use in typedefs AC_CHECK_SIZEOF([char], [], [[]]) AC_CHECK_SIZEOF([short], [], [[]]) diff --git a/re2c/src/util/temp_file.cc b/re2c/src/util/temp_file.cc index 7141df9c..97ebbbe7 100644 --- a/re2c/src/util/temp_file.cc +++ b/re2c/src/util/temp_file.cc @@ -1,32 +1,45 @@ +#include "config.h" #include #include "src/msg/msg.h" #include "src/util/temp_file.h" -#if defined(_WIN32) && !defined(__MINGW32__) +#if !defined(_MSVC) \ + && defined(HAVE_FCNTL_H) \ + && defined(HAVE_SYS_STAT_H) \ + && defined(HAVE_SYS_TYPES_H) \ + && defined(HAVE_UNISTD_H) + +// POSIX +#include +#include +#include +#include +#define OPEN(fn) open(fn, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR) +#define FDOPEN(fd) fdopen(fd, "w") +#define CLOSE(fd) close(fd) + +#elif defined(_MSVC) \ + && defined(HAVE_IO_H) // MSVC #include -#define OPEN _open -#define FDOPEN _fdopen -#define FLAGS _O_CREAT | _O_EXCL | _O_RDWR -#define MODE _S_IREAD | _S_IWRITE +#define OPEN(fn) _open(fn, _O_CREAT | _O_EXCL | _O_RDWR, _S_IREAD | _S_IWRITE) +#define FDOPEN(fd) _fdopen(fd, "w") +#define CLOSE(fd) _close(fd) #else -// POSIX -#include -#include -#include -#define OPEN open -#define FDOPEN fdopen -#define FLAGS O_CREAT | O_EXCL | O_RDWR -#define MODE S_IRUSR | S_IWUSR +// stubs +#define OPEN(fn) -1 +#define FDOPEN(fd) NULL +#define CLOSE -1 #endif namespace re2c { +// In C++11, all this could be substituted with fopen(..., "x") FILE *temp_file(std::string &fname) { // append "random enough" suffix to filename @@ -37,9 +50,12 @@ FILE *temp_file(std::string &fname) // open file for writing, unless it exists already FILE *f = NULL; - int fd = OPEN(fname.c_str(), FLAGS, MODE); + int fd = OPEN(fname.c_str()); if (fd != -1) { - f = FDOPEN(fd, "w"); + f = FDOPEN(fd); + if (!f) { + CLOSE(fd); + } } // we don't try too hard @@ -53,4 +69,4 @@ FILE *temp_file(std::string &fname) #undef OPEN #undef FDOPEN -#undef FLAGS +#undef CLOSE -- 2.40.0