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>
This commit is contained in:
parent
3ff53df7b4
commit
260eec2927
@ -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 xwrite(int fd, const void *buf, size_t len);
|
||||||
extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
|
extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
|
||||||
extern int xdup(int fd);
|
extern int xdup(int fd);
|
||||||
|
extern FILE *xfopen(const char *path, const char *mode);
|
||||||
extern FILE *xfdopen(int fd, const char *mode);
|
extern FILE *xfdopen(int fd, const char *mode);
|
||||||
extern int xmkstemp(char *template);
|
extern int xmkstemp(char *template);
|
||||||
extern int xmkstemp_mode(char *template, int mode);
|
extern int xmkstemp_mode(char *template, int mode);
|
||||||
|
21
wrapper.c
21
wrapper.c
@ -346,6 +346,27 @@ int xdup(int fd)
|
|||||||
return ret;
|
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 *xfdopen(int fd, const char *mode)
|
||||||
{
|
{
|
||||||
FILE *stream = fdopen(fd, mode);
|
FILE *stream = fdopen(fd, mode);
|
||||||
|
Loading…
Reference in New Issue
Block a user