1
0
forked from bonsai/harakit

cat(1p): cleanup

This commit is contained in:
Emma Tebibyte 2023-08-14 11:45:43 -06:00
parent 0c290646ec
commit f041ae5d63
Signed by untrusted user: emma
GPG Key ID: 6D661C738815E7DD

View File

@ -20,6 +20,7 @@
#include <errno.h> #include <errno.h>
#include <sysexits.h> #include <sysexits.h>
#include <sys/stat.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
@ -29,26 +30,26 @@ void cat(FILE *file, bool u) {
int p = 0; /* index counter for bytes in buffered reading */ int p = 0; /* index counter for bytes in buffered reading */
char buf[4096]; /* buffer for buffered reading */ char buf[4096]; /* buffer for buffered reading */
while (byte != EOF) { if (u) {
byte = fgetc(file); while (byte != EOF) {
byte = fgetc(file);
if (u) {
putchar(byte); putchar(byte);
} else { }
} else {
while (byte != EOF) {
byte = fgetc(file);
if (p > sizeof(buf)) { if (p > sizeof(buf)) {
fputs(buf, stdout); fputs(buf, stdout);
p = 0; p = 0;
} else {
buf[p] = byte;
p += 1;
} }
buf[p] = byte;
p += 1;
} }
fwrite(buf, 1, p, stdout);
fflush(stdout);
} }
fwrite(buf, 1, p, stdout);
fflush(stdout);
if (file != stdin) { fclose(file); }
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
@ -91,11 +92,20 @@ int main(int argc, char *argv[]) {
} }
FILE *file; FILE *file;
struct stat stats;
for (i = optind; i < argc; i++) { for (i = optind; i < argc; i++) {
if (argv[i][0] == '-' && argv[i][1] != '\0') { if (argv[i][0] == '-') {
continue; switch (argv[i][1]) {
} else if (argv[i][0] == '-' && argv[i][1] == '\0') { case '\0':
file = stdin; file = stdin;
break;
default:
continue;
}
} else if (stat(argv[i], &stats) == 0 && S_ISDIR(stats.st_mode)) {
fprintf(stderr, "%s: %s: Is a directory.\n", argv[0], argv[i]);
return EX_NOINPUT;
} else if ((file = fopen(argv[i], "r")) == NULL) { } else if ((file = fopen(argv[i], "r")) == NULL) {
switch (errno) { switch (errno) {
case EACCES: case EACCES:
@ -118,7 +128,9 @@ int main(int argc, char *argv[]) {
return EX_UNAVAILABLE; return EX_UNAVAILABLE;
} }
} }
cat(file, u); cat(file, u);
if (file != stdin) { fclose(file); }
} }
return EX_OK; return EX_OK;