diff --git a/src/filterdiff.c b/src/filterdiff.c index b616f71d..d0a77408 100644 --- a/src/filterdiff.c +++ b/src/filterdiff.c @@ -1828,15 +1828,10 @@ int main (int argc, char *argv[]) if (inplace_mode) { /* Redirect stdout to temporary file for in-place processing */ - FILE *temp_output = xtmpfile(); - FILE *old_stdout = stdout; - stdout = temp_output; + FILE *temp_output = redirectfd(stdout); filterdiff (f, argv[i]); - /* Restore stdout */ - stdout = old_stdout; - /* Write temp file contents back to original file */ if (write_file_inplace(argv[i], temp_output) != 0) { error (EXIT_FAILURE, errno, "failed to write %s", argv[i]); diff --git a/src/util.c b/src/util.c index a977137c..4f46f3c4 100644 --- a/src/util.c +++ b/src/util.c @@ -116,6 +116,30 @@ FILE *xtmpfile (void) return ret; } +FILE *redirectfd (FILE* fd) +{ + FILE *ret; + char *tmpfname; + char *tmpdir = getenv ("TMPDIR"); + size_t tmpdirlen; + + if (tmpdir == NULL) { + tmpdir = P_tmpdir; + } + + tmpdirlen = strlen (tmpdir); + tmpfname = xmalloc (tmpdirlen + 8); + strcpy (tmpfname, tmpdir); + strcpy (tmpfname + tmpdirlen, "/XXXXXX"); + close(mkstemp(tmpfname)); + ret = freopen (tmpfname, "w+b", fd); + if (ret == NULL) + error (EXIT_FAILURE, errno, "freopen"); + unlink (tmpfname); + free (tmpfname); + return ret; +} + /* * Pattern operations. */ diff --git a/src/util.h b/src/util.h index a5882a4a..34f372b1 100644 --- a/src/util.h +++ b/src/util.h @@ -42,6 +42,8 @@ char *xstrndup (const char *s, const size_t n); int xmkstemp (char *pattern); /* safe tmpfile */ FILE *xtmpfile (void); +/* redirect fd to temp file */ +FILE *redirectfd (FILE* fd); FILE *xopen(const char *file, const char *mode); FILE *xopen_seekable(const char *file, const char *mode);