Commits

Evan Gates  committed 203bee0

clean up and generalize cw

  • Participants
  • Parent commits dfe417c

Comments (0)

Files changed (1)

+#include <stdlib.h>
 #include <sys/stat.h>
 #include <errno.h>
 #include <sys/select.h>
 #include <sys/inotify.h>
 #include <stdio.h>
 
+mode_t type = 0;
+mode_t perm = 0600;
+
+void usage(void)
+{
+	printf("Usage: cw [-c|-f] infile outfile\n");
+	exit(1);
+}
+
+FILE *mopen(char *path, char *mode)
+{
+	struct stat st;
+	FILE *f;
+
+	if (stat(path, &st) < 0 && errno == ENOENT) {
+		if (!type)
+			err(1, "file %s does not exist", path);
+		else if (mknod(path, type | perm, 0) < 0)
+			err(1, "file %s could not be created", path);
+	}
+
+	warnx("Opening %s (if it's a fifo, waiting for the other side to be opened)...", path);
+
+	if ((f = fopen(path, mode)) == NULL)
+		err(1, "failed to fopen %s", path);
+
+	warnx("...OK");
+
+	return f;
+}
 
 int main(int argc, char **argv)
 {
-	int evq, in_wd;
+	int evq, in_wd, i;
 	FILE *in, *out;
 	char buf[4096];
 	fd_set rd;
-	struct stat st;
 	struct inotify_event *cur;
 
+	for (i = 1; i < argc; i++) {
+		if (argv[i][0] != '-')
+			break;
+		if (argv[i][2] != '\0')
+			usage();
+		switch (argv[i][1]) {
+			case 'c' : type = S_IFREG; break; // create regular files
+			case 'f' : type = S_IFIFO; break; // create fifos
+			// is it worth doing character, block, and socket too?
+			default  : usage();
+		}
+	}
+	if (i + 1 >= argc)
+		usage();
+
+	in = mopen(argv[i], "r");
+
+	while (fgets(buf, sizeof(buf), in))
+		fputs(buf, stdout);
+
+	out = mopen(argv[i + 1], "w");
+
+	printf("-------------------- new text starts here --------------------\n");
+
 	if ((evq = inotify_init()) < 0)
 		err(1, "failed inotify_init()");
 
-	if ((in_wd = inotify_add_watch(evq, argv[1], IN_MODIFY)) < 0)
+	if ((in_wd = inotify_add_watch(evq, argv[i], IN_MODIFY)) < 0)
 		err(1, "failed inotify_add_watch()");
 
-	warnx("Opening %s (if it's a fifo, waiting for other side to be opened)...", argv[1]);
-
-	if ((in = fopen(argv[1], "r")) == NULL)
-		err(1, "failed fopen()");
-
-	warnx("...OK");
-
-	if (stat(argv[2], &st) < 0 && errno == ENOENT && mkfifo(argv[2], 0700) < 0)
-		err(1, "failed to mkfifo %s\n", argv[2]);
-
-	while (fgets(buf, sizeof(buf), in))
-		fputs(buf, stdout);
-
-	warnx("Opening %s (if it's a fifo, waiting for other side to be opened)...", argv[2]);
-
-	if ((out = fopen(argv[2], "w")) == NULL)
-		err(1, "failed fopen()");
-
-	warnx("...OK");
-
-	printf("-------------------- new text starts here --------------------\n");
-
 	for (;;) {
 		FD_ZERO(&rd);
 		FD_SET(0, &rd);