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>

Paul Tan committed Aug 4, 2015 at 21:51 UTC 260eec292736388831958637eccdcf1a8f00e14d
2 files changed +22
git-compat-util.h
+1
@@ -722,6 +722,7 @@ extern ssize_t xread(int fd, void *buf, size_t len);
722 extern ssize_t xwrite(int fd, const void *buf, size_t len);
723 extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
724 extern int xdup(int fd);
725 +extern FILE *xfopen(const char *path, const char *mode);
726 extern FILE *xfdopen(int fd, const char *mode);
727 extern int xmkstemp(char *template);
728 extern int xmkstemp_mode(char *template, int mode);
wrapper.c
+21
@@ -346,6 +346,27 @@ int xdup(int fd)
346 return ret;
347 }
348
349 +/**
350 + * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
351 + */
352 +FILE *xfopen(const char *path, const char *mode)
353 +{
354 + for (;;) {
355 + FILE *fp = fopen(path, mode);
356 + if (fp)
357 + return fp;
358 + if (errno == EINTR)
359 + continue;
360 +
361 + if (*mode && mode[1] == '+')
362 + die_errno(_("could not open '%s' for reading and writing"), path);
363 + else if (*mode == 'w' || *mode == 'a')
364 + die_errno(_("could not open '%s' for writing"), path);
365 + else
366 + die_errno(_("could not open '%s' for reading"), path);
367 + }
368 +}
369 +
370 FILE *xfdopen(int fd, const char *mode)
371 {
372 FILE *stream = fdopen(fd, mode);