summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLieuwe Rooijakkers <lieuwerooijakkers@gmail.com>2024-07-25 23:29:18 +0200
committerLieuwe Rooijakkers <lieuwerooijakkers@gmail.com>2024-07-25 23:29:18 +0200
commite9c8b358027e5b0d3f4787d74957d1355f87d5bc (patch)
tree051d17c27fbc54afb8b45ba317c8cf6bff95750b
parent079dbce33c5f064ae3eb1da0b8f3f1e8fed784a9 (diff)
rn
-rw-r--r--src/rn.c97
1 files changed, 97 insertions, 0 deletions
diff --git a/src/rn.c b/src/rn.c
new file mode 100644
index 0000000..11c8b45
--- /dev/null
+++ b/src/rn.c
@@ -0,0 +1,97 @@
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "util/versie.h"
+#include "io/lines.h"
+
+static void usage(FILE *f) {
+ fprintf(f,
+ "Gebruik: rn [-hV] [BESTAND]...\n"
+ "\n"
+ "Nummereer elke regel van elk BESTAND.\n"
+ "Als geen bestanden gegeven zijn, of het bestand is -, nummereer dan standaard invoer.\n"
+ "\n"
+ " -p Regelnummers per BESTAND.\n"
+ " -h Toon deze hulptekst\n"
+ " -V Toon versienummer\n");
+}
+
+// Returns pointer to argument array containing the file names
+static char** parse_options(int argc, char **argv, bool *perFile) {
+ int opt;
+ while ((opt = getopt(argc, argv, "phV")) != -1) {
+ switch (opt) {
+ case 'p':
+ *perFile = true;
+ break;
+
+ case 'h':
+ usage(stdout);
+ exit(0);
+
+ case 'V':
+ drukkedoos_print_versie(stdout);
+ exit(0);
+
+ case '?':
+ usage(stderr);
+ exit(1);
+ }
+ }
+
+ return argv + optind;
+}
+
+static void process(const char *fname, FILE *file, bool perFile, size_t *n) {
+ if (perFile) *n = 1;
+
+ struct file_lines fl;
+ if (!file_lines_open("rn", fname, file, &fl)) exit(1);
+
+ while (true) {
+ struct string_view sv;
+ if (!file_lines_read(&fl, &sv)) break;
+
+ printf("%6lu ", *n);
+ fwrite(sv.s, 1, sv.len, stdout);
+ printf("\n");
+
+ *n += 1;
+ }
+
+ file_lines_close(&fl);
+}
+
+int entry_rn(int argc, char **argv) {
+ bool perFile = false;
+ char **args = parse_options(argc, argv, &perFile);
+
+ size_t n = 1;
+
+ if (*args == NULL) {
+ process("stdin", stdin, perFile, &n);
+ return 0;
+ }
+
+ while (*args != NULL) {
+ if (!strcmp(*args, "-")) {
+ process("stdin", stdin, perFile, &n);
+ } else {
+ FILE *file = fopen(*args, "r");
+ if (file == NULL) {
+ fprintf(stderr, "rn: %s: kon bestand niet openen\n", *args);
+ return 1;
+ }
+
+ process(*args, file, perFile, &n);
+ fclose(file);
+ }
+
+ args++;
+ }
+
+ return 0;
+}