wm: glendy

Download patch

ref: e72aa2d79aff1b39b24c98ad9d02c487a0014ad5
parent: a62bb92d35278237f1fdf268ad41d11af51e7fba
author: mkf <mkf@cloud9p.org>
date: Thu May 9 17:04:25 EDT 2024

unix.[ch]: add plan9-alike fmt functions

main difference is printf and friends work on a FILE, while plan 9 and friends work on a fd, an fd can't be buffered and is a bit slower, but it's easier than making a socket to act like as a FILE.

i also like their name. ☺

--- a/unix.c
+++ b/unix.c
@@ -1,6 +1,7 @@
 #include <stdio.h>
 #include <stdarg.h>
 #include <stdlib.h>
+#include <unistd.h>
 #include "unix.h"
 
 Point
@@ -35,7 +36,7 @@
 int
 eqpt(Point p, Point q)
 {
-	return p.x==q.x && p.y==q.y;
+	return p.x == q.x && p.y == q.y;
 }
 
 int
@@ -43,3 +44,54 @@
 {
 	return rand() % n;
 }
+
+/*
+ * i'm well aware of printf and it's friends
+ * but i had to prefer one (Plan 9) interface over other one (POSIX/ANSI)
+ */
+int
+vsprint(char *out, char *fmt, va_list arg)
+{
+	int n;
+	n = vsprintf(out, fmt, arg);
+	return n;
+}
+
+int
+sprint(char *out, char *fmt, ...)
+{
+	int n;
+	va_list arg;
+	va_start(arg, fmt);
+	
+	n = vsprint(out, fmt, arg);
+	va_end(arg);
+	return n;
+}
+
+int
+vfprint(int fd, char *fmt, va_list arg)
+{
+	char *s = (char*)malloc(1024);
+	int n;
+
+	n = vsprint(s, fmt, arg);
+	if(write(fd, s, n) < n)
+		perror("couldn't write");
+	free(s);
+	return n;
+}
+
+int
+fprint(int fd, char *fmt, ...)
+{
+	int n;
+	va_list arg;
+	va_start(arg, fmt);
+	
+	n = vfprint(fd, fmt, arg);
+	va_end(arg);
+	return n;
+}
+
+
--- a/unix.h
+++ b/unix.h
@@ -1,7 +1,10 @@
 /* this code is uglier than what it should be */
 #pragma once
 #include <string.h>
-#include <stdio.h> /* replace with plan 9's print? */
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdarg.h>
 
 /* uncomment if your compiler doesn't support it (ANSI, C99)
 #define _Noreturn
@@ -21,3 +24,9 @@
 _Noreturn void exits(char *s);
 int eqpt(Point p, Point q);
 int nrand(int n);
+
+/* fmt */
+int vsprint(char *out, char *fmt, va_list arg);
+int sprint(char *out, char *fmt, ...);
+int vfprint(int fd, char *fmt, va_list arg);
+int fprint(int fd, char *fmt, ...);