[PATCH/WIP 2/8] wrapper: implement xfopen()

2015-05-27 Thread Paul Tan
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 pyoka...@gmail.com
---
 git-compat-util.h |  1 +
 wrapper.c | 19 +++
 2 files changed, 20 insertions(+)

diff --git a/git-compat-util.h b/git-compat-util.h
index 9745962..914d450 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -723,6 +723,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 971665a..d5ed780 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -329,6 +329,25 @@ 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)
+{
+   FILE *fp;
+
+   assert(path);
+   assert(mode);
+   fp = fopen(path, mode);
+   if (!fp) {
+   if (*mode == 'w' || *mode == 'a')
+   die_errno(_(could not open '%s' for writing), path);
+   else
+   die_errno(_(could not open '%s' for reading), path);
+   }
+   return fp;
+}
+
 FILE *xfdopen(int fd, const char *mode)
 {
FILE *stream = fdopen(fd, mode);
-- 
2.1.4

--
To unsubscribe from this list: send the line unsubscribe git in
the body of a message to majord...@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html


Re: [PATCH/WIP 2/8] wrapper: implement xfopen()

2015-05-27 Thread Jeff King
On Wed, May 27, 2015 at 09:33:32PM +0800, Paul Tan wrote:

 +/**
 + * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
 + */
 +FILE *xfopen(const char *path, const char *mode)
 +{
 + FILE *fp;
 +
 + assert(path);
 + assert(mode);
 + fp = fopen(path, mode);
 + if (!fp) {
 + if (*mode == 'w' || *mode == 'a')
 + die_errno(_(could not open '%s' for writing), path);

This misses r+. I don't think we use that in our code currently, but
if we're going to introduce a wrapper like this, I think it makes sense
to cover all cases.

-Peff
--
To unsubscribe from this list: send the line unsubscribe git in
the body of a message to majord...@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html