smu: Re-add processing from STDIN

This commit is contained in:
Enno Tensing 2025-01-21 20:12:16 +01:00
parent 29d314255d
commit e195f586cd
Signed by: tenno
GPG key ID: 95265603BD36E66C

44
smu.c
View file

@ -16,6 +16,7 @@
#include <fcntl.h> #include <fcntl.h>
#include <errno.h> #include <errno.h>
#define CHARWIDTH 4
#define LENGTH(x) sizeof(x) / sizeof(x[0]) #define LENGTH(x) sizeof(x) / sizeof(x[0])
#define ADDC(b, i, a) \ #define ADDC(b, i, a) \
do { \ do { \
@ -119,7 +120,7 @@ char *read_file(const char *path, off64_t file_size)
int fd = open(path, O_LARGEFILE | O_NONBLOCK); int fd = open(path, O_LARGEFILE | O_NONBLOCK);
ssize_t bytes; ssize_t bytes;
char *buf = calloc(file_size + 4, sizeof(char)); char *buf = calloc(file_size + CHARWIDTH, sizeof(char));
if (!buf) { if (!buf) {
perror(""); perror("");
@ -714,6 +715,7 @@ int main(int argc, char *argv[])
char *buffer = NULL; char *buffer = NULL;
const char *path = "STDIN"; const char *path = "STDIN";
int i; int i;
int ret = EXIT_SUCCESS;
for (i = 1; i < argc; i++) { for (i = 1; i < argc; i++) {
if (!strcmp("-v", argv[i])) if (!strcmp("-v", argv[i]))
@ -730,19 +732,49 @@ int main(int argc, char *argv[])
argv[0]); argv[0]);
} }
if (i < argc) if (i < argc) {
path = argv[i]; path = argv[i];
off64_t len = get_file_size(path); off64_t len = get_file_size(path);
if (len == -1) { if (len == -1) {
eprint("%s: %s: %s\n", argv[0], path, strerror(errno)); eprint("%s: %s: %s\n", argv[0], path, strerror(errno));
return EXIT_FAILURE; ret = EXIT_FAILURE;
goto exit;
} }
buffer = read_file(path, len); buffer = read_file(path, len);
if (!buffer) if (!buffer) {
return EXIT_FAILURE; perror("");
ret = EXIT_FAILURE;
goto exit;
}
buffer[len] = '\0'; buffer[len] = '\0';
process(buffer, buffer + len, 1); process(buffer, buffer + len, 1);
free(buffer); free(buffer);
return EXIT_SUCCESS; } else {
size_t buffer_size = 1024 * CHARWIDTH;
buffer = calloc(buffer_size + CHARWIDTH, sizeof(char));
if (!buffer) {
perror("");
ret = EXIT_FAILURE;
goto exit;
}
size_t read_bytes;
while (1) {
read_bytes = read(STDIN_FILENO, buffer, buffer_size);
if (read_bytes <= 0) {
if (errno) {
perror("");
ret = EXIT_FAILURE;
}
free(buffer);
break;
}
buffer[read_bytes] = '\0';
process(buffer, buffer + read_bytes, 1);
}
}
exit:
return ret;
} }