summaryrefslogtreecommitdiff
path: root/wrapper.c
diff options
context:
space:
mode:
authorPaul Tan <pyokagan@gmail.com>2015-08-04 21:51:23 +0800
committerJunio C Hamano <gitster@pobox.com>2015-08-04 22:02:11 -0700
commit260eec292736388831958637eccdcf1a8f00e14d (patch)
tree8492c821dac8943a3b03ef25c5a3cecb1887b8c0 /wrapper.c
parent3ff53df7b4cbc331d302181d2d6644f4cb860a52 (diff)
downloadgit-260eec292736388831958637eccdcf1a8f00e14d.tar.gz
wrapper: implement xfopen()
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. Helped-by: Jeff King <peff@peff.net> Helped-by: Johannes Schindelin <johannes.schindelin@gmx.de> Helped-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Paul Tan <pyokagan@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Diffstat (limited to 'wrapper.c')
-rw-r--r--wrapper.c21
1 files changed, 21 insertions, 0 deletions
diff --git a/wrapper.c b/wrapper.c
index 0a4502d232..e451463431 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -346,6 +346,27 @@ 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)
+{
+ for (;;) {
+ FILE *fp = fopen(path, mode);
+ if (fp)
+ return fp;
+ if (errno == EINTR)
+ continue;
+
+ if (*mode && mode[1] == '+')
+ die_errno(_("could not open '%s' for reading and writing"), path);
+ else if (*mode == 'w' || *mode == 'a')
+ die_errno(_("could not open '%s' for writing"), path);
+ else
+ die_errno(_("could not open '%s' for reading"), path);
+ }
+}
+
FILE *xfdopen(int fd, const char *mode)
{
FILE *stream = fdopen(fd, mode);