[PATCH v4 02/44] wrapper: implement xfopen()
From: Paul Tan <hidden>
Date: 2016-06-15 23:05:33
Subsystem:
the rest · Maintainer:
Linus Torvalds
A common usage pattern of fopen() is to check if it succeeded, and die()
if it failed:
FILE *fp = fopen(path, "w");
if (!fp)
die_errno(_("could not open '%s' for writing"), path);
Implement a wrapper function xfopen() for the above, so that we can save
a few lines of code and make the die() messages consistent.
Signed-off-by: Paul Tan <redacted>
---
git-compat-util.h | 1 +
wrapper.c | 18 ++++++++++++++++++
2 files changed, 19 insertions(+)
diff --git a/git-compat-util.h b/git-compat-util.h
index e168dfd..392da79 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h@@ -722,6 +722,7 @@ extern ssize_t xread(int fd, void *buf, size_t len); extern ssize_t xwrite(int fd, const void *buf, size_t len); extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset); extern int xdup(int fd); +extern FILE *xfopen(const char *path, const char *mode); extern FILE *xfdopen(int fd, const char *mode); extern int xmkstemp(char *template); extern int xmkstemp_mode(char *template, int mode);
diff --git a/wrapper.c b/wrapper.c
index 7e13ae0..f127eb3 100644
--- a/wrapper.c
+++ b/wrapper.c@@ -336,6 +336,24 @@ int xdup(int fd) return ret; } +/** + * xfopen() is the same as fopen(), but it die()s if the fopen() fails. + */ +FILE *xfopen(const char *path, const char *mode) +{ + assert(path); + assert(mode); + + for (;;) { + FILE *fp = fopen(path, mode); + if (fp) + return fp; + if (errno == EINTR) + continue; + die_errno(_("could not open '%s'"), path); + } +} + FILE *xfdopen(int fd, const char *mode) { FILE *stream = fdopen(fd, mode);
--
2.5.0.rc0.76.gb2c6e93