wrapper.c: wrapper to open a file, fprintf then close
authorNguyễn Thái Ngọc Duy <pclouds@gmail.com>
Sun, 30 Nov 2014 08:24:45 +0000 (15:24 +0700)
committerJunio C Hamano <gitster@pobox.com>
Mon, 1 Dec 2014 19:00:16 +0000 (11:00 -0800)
Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
cache.h
wrapper.c
diff --git a/cache.h b/cache.h
index 9dc6ae0b57d443e1804984f335d57c5d42992d0b..43c2e52585415cd1f2344c7bdf3ac442c8f2a1db 100644 (file)
--- a/cache.h
+++ b/cache.h
@@ -1499,6 +1499,8 @@ static inline ssize_t write_str_in_full(int fd, const char *str)
 {
        return write_in_full(fd, str, strlen(str));
 }
+__attribute__((format (printf, 3, 4)))
+extern int write_file(const char *path, int fatal, const char *fmt, ...);
 
 /* pager.c */
 extern void setup_pager(void);
index 007ec0d8eac529579cc00b14f9baaddb7ac68487..a2dff8e5be019f0aca58f3858d7a880f290b69e1 100644 (file)
--- a/wrapper.c
+++ b/wrapper.c
@@ -550,3 +550,34 @@ char *xgetcwd(void)
                die_errno(_("unable to get current working directory"));
        return strbuf_detach(&sb, NULL);
 }
+
+int write_file(const char *path, int fatal, const char *fmt, ...)
+{
+       struct strbuf sb = STRBUF_INIT;
+       va_list params;
+       int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
+       if (fd < 0) {
+               if (fatal)
+                       die_errno(_("could not open %s for writing"), path);
+               return -1;
+       }
+       va_start(params, fmt);
+       strbuf_vaddf(&sb, fmt, params);
+       va_end(params);
+       if (write_in_full(fd, sb.buf, sb.len) != sb.len) {
+               int err = errno;
+               close(fd);
+               strbuf_release(&sb);
+               errno = err;
+               if (fatal)
+                       die_errno(_("could not write to %s"), path);
+               return -1;
+       }
+       strbuf_release(&sb);
+       if (close(fd)) {
+               if (fatal)
+                       die_errno(_("could not close %s"), path);
+               return -1;
+       }
+       return 0;
+}