From f3e452a35ab5fd1808be7a50652b54dc3222ba6e Mon Sep 17 00:00:00 2001
From: Rob Landley <rob@landley.net>
Date: Mon, 8 Jan 2007 02:49:39 -0500
Subject: Add rewrite(), writeall(),and xwrite() to match the read versions.

---
 lib/functions.c | 31 +++++++++++++++++++++++++++++--
 lib/lib.h       |  3 +++
 2 files changed, 32 insertions(+), 2 deletions(-)

(limited to 'lib')

diff --git a/lib/functions.c b/lib/functions.c
index 990c34fa..e37887ed 100644
--- a/lib/functions.c
+++ b/lib/functions.c
@@ -165,13 +165,21 @@ FILE *xfopen(char *path, char *mode)
 // Read from file handle, retrying if interrupted.
 ssize_t reread(int fd, void *buf, size_t count)
 {
-	ssize_t len;
 	for (;;) {
-		len = read(fd, buf, count);
+		ssize_t len = read(fd, buf, count);
 		if (len >= 0  || errno != EINTR) return len;
 	}
 }
 
+// Write to file handle, retrying if interrupted.
+ssize_t rewrite(int fd, void *buf, size_t count)
+{
+	for (;;) {
+		ssize_t len = write(fd, buf, count);
+		if (len >= 0 || errno != EINTR) return len;
+	}
+}
+
 // Keep reading until full or EOF
 ssize_t readall(int fd, void *buf, size_t count)
 {
@@ -186,12 +194,31 @@ ssize_t readall(int fd, void *buf, size_t count)
 	return count;
 }
 
+// Keep writing until done or EOF
+ssize_t writeall(int fd, void *buf, size_t count)
+{
+	size_t len = 0;
+	while (len<count) {
+		int i = rewrite(fd, buf, count);
+		if (!i) return len;
+		if (i<0) return i;
+		count += i;
+	}
+
+	return count;
+}
+
 // Die if we can't fill a buffer
 void xread(int fd, char *buf, size_t count)
 {
 	if (count != readall(fd, buf, count)) perror_exit("xread");
 }	
 
+void xwrite(int fd, char *buf, size_t count)
+{
+	if (count != writeall(fd, buf, count)) perror_exit("xwrite");
+}
+
 char *xgetcwd(void)
 {
 	char *buf = getcwd(NULL, 0);
diff --git a/lib/lib.h b/lib/lib.h
index cb140275..0fe2db6a 100644
--- a/lib/lib.h
+++ b/lib/lib.h
@@ -42,8 +42,11 @@ int xcreate(char *path, int flags, int mode);
 int xopen(char *path, int flags);
 FILE *xfopen(char *path, char *mode);
 ssize_t reread(int fd, void *buf, size_t count);
+ssize_t rewrite(int fd, void *buf, size_t count);
 ssize_t readall(int fd, void *buf, size_t count);
+ssize_t writeall(int fd, void *buf, size_t count);
 void xread(int fd, char *buf, size_t count);
+void xwrite(int fd, char *buf, size_t count);
 char *xgetcwd(void);
 char *xabspath(char *path);
 struct string_list *find_in_path(char *path, char *filename);
-- 
cgit v1.2.3