commit 6e39f199fa18107d836510fdc7c526856658ac80
parent 8f93ad24cc73be63b1e0f119b9d0e55a7ce79f2c
Author: Louis Burda <quent.burda@gmail.com>
Date: Fri, 2 Aug 2024 21:02:56 +0200
Make more readable
Diffstat:
M | typetest.c | | | 69 | +++++++++++++++++++++++++++++++++++++++------------------------------ |
1 file changed, 39 insertions(+), 30 deletions(-)
diff --git a/typetest.c b/typetest.c
@@ -5,6 +5,7 @@
#include <time.h>
#include <stdio.h>
#include <string.h>
+#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
@@ -46,10 +47,10 @@ static const int style_right[] = { STYLE_GREEN_FG, STYLE_END };
static const int style_reset[] = { STYLE_RESET, STYLE_END };
static const int style_preview[] = { STYLE_GREY_FG, STYLE_END };
-struct termios oldt;
+static struct termios old_termios;
-int typed = 0;
-float gcps;
+static int typed = 0;
+static float gcps;
void
print_style(const int *props)
@@ -167,15 +168,18 @@ quit:
}
int
-getl(FILE *f, char *buf, size_t size)
+readline(FILE *f, char *buf, size_t size)
{
- int i;
-
do {
if (!fgets(buf, size, f)) return 1;
- for (i = strlen(buf) - 1; *buf; buf[i--] = '\0')
- if (!strchr("\n\r", buf[i])) break;
+ for (ssize_t i = strlen(buf) - 1; i >= 0; i--) {
+ if (buf[i] == '\r' || buf[i] == '\n')
+ buf[i] = '\0';
+ else
+ break;
+ }
+ if (strlen(buf) == 0) continue;
} while (!*buf);
return 0;
@@ -184,48 +188,53 @@ getl(FILE *f, char *buf, size_t size)
void
reset()
{
- tcsetattr(0, TCSANOW, &oldt);
+ tcsetattr(0, TCSANOW, &old_termios);
}
int
main(int argc, const char **argv)
{
- char cur[256], next[256];
- struct termios t;
- int eof;
- FILE *f;
-
- if (argc < 2) {
- printf("Usage: typetest FILE\n");
- return 1;
+ const char *path = NULL;
+ bool retry = true;
+
+ for (const char **arg = argv + 1; *arg; arg++) {
+ if (!strcmp(*arg, "-R")) {
+ retry = false;
+ } else if (!path) {
+ path = *arg;
+ } else {
+ break;
+ }
}
+ if (!path) errx(1, "missing file argument");
- if (!(f = fopen(argv[1], "r")))
- errx(1, "Failed to read file");
+ FILE *file = fopen(path, "r");
+ if (!file) err(1, "fopen");
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
- tcgetattr(0, &t);
- memcpy(&oldt, &t, sizeof(struct termios));
+ struct termios termios;
+ tcgetattr(0, &termios);
+ old_termios = termios;
- cfmakeraw(&t);
+ cfmakeraw(&termios);
- if (!tcsetattr(0, TCSANOW, &t)) atexit(reset);
+ if (!tcsetattr(0, TCSANOW, &termios)) atexit(reset);
- if (getl(f, next, sizeof(next)))
+ char line[256], next_line[256];
+ if (readline(file, next_line, sizeof(next_line)))
errx(1, "Empty input file");
- for (eof = 0; !eof; ) {
- memcpy(cur, next, sizeof(cur));
- eof |= getl(f, next, sizeof(next));
- if (type(cur, eof ? "" : next)) break;
+ for (bool eof = 0; !eof; ) {
+ strcpy(line, next_line);
+ eof |= readline(file, next_line, sizeof(next_line));
+ if (type(line, eof ? "" : next_line)) break;
}
if (gcps) {
printf("CPM: %0.2f\n\r", gcps * 60);
- printf("WPM: %0.2f\n\r", gcps * 12);
}
- fclose(f);
+ fclose(file);
}