Skip to content

Commit 316e53e

Browse files
pcloudsgitster
authored andcommitted
wrapper.c: wrapper to open a file, fprintf then close
Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent 31e26eb commit 316e53e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

cache.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,6 +1499,8 @@ static inline ssize_t write_str_in_full(int fd, const char *str)
14991499
{
15001500
return write_in_full(fd, str, strlen(str));
15011501
}
1502+
__attribute__((format (printf, 3, 4)))
1503+
extern int write_file(const char *path, int fatal, const char *fmt, ...);
15021504

15031505
/* pager.c */
15041506
extern void setup_pager(void);

wrapper.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,3 +550,34 @@ char *xgetcwd(void)
550550
die_errno(_("unable to get current working directory"));
551551
return strbuf_detach(&sb, NULL);
552552
}
553+
554+
int write_file(const char *path, int fatal, const char *fmt, ...)
555+
{
556+
struct strbuf sb = STRBUF_INIT;
557+
va_list params;
558+
int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
559+
if (fd < 0) {
560+
if (fatal)
561+
die_errno(_("could not open %s for writing"), path);
562+
return -1;
563+
}
564+
va_start(params, fmt);
565+
strbuf_vaddf(&sb, fmt, params);
566+
va_end(params);
567+
if (write_in_full(fd, sb.buf, sb.len) != sb.len) {
568+
int err = errno;
569+
close(fd);
570+
strbuf_release(&sb);
571+
errno = err;
572+
if (fatal)
573+
die_errno(_("could not write to %s"), path);
574+
return -1;
575+
}
576+
strbuf_release(&sb);
577+
if (close(fd)) {
578+
if (fatal)
579+
die_errno(_("could not close %s"), path);
580+
return -1;
581+
}
582+
return 0;
583+
}

0 commit comments

Comments
 (0)