cat(1p): fix unbuffered output

This commit is contained in:
2023-08-07 20:38:57 -06:00
parent 9adde985d9
commit c8d6e9f5e4
2 changed files with 94 additions and 26 deletions

View File

@@ -28,9 +28,9 @@
#include <unistd.h>
int main(int argc, char *argv[]) {
int i = 1;
bool u = false;
int opt;
FILE *file;
char *usage_text = "(-u) [file...]";
int buf_size = strlen(argv[0]) + strlen("Usage: ") + strlen(usage_text) + 3;
char *usage = calloc(buf_size, buf_size);
@@ -39,8 +39,7 @@ int main(int argc, char *argv[]) {
snprintf(usage, buf_size, "Usage: %s (-u) [file...]\n", argv[0])
) < 0 ) {}
int opt;
extern int optind;
while ((opt = getopt(argc, argv, "u")) != -1) {
switch(opt) {
/*
@@ -50,17 +49,17 @@ int main(int argc, char *argv[]) {
* without delay as each is read.
*/
case 'u':
i = 2;
u = true;
break;
default:
break;
}
}
argv += optind;
argc -= optind;
FILE *file;
for (; i <= (argc - 1); i++) {
for (int i = 0; i < argc; i++) {
int byte = 0;
/*
* From cat(1p):
*
@@ -72,33 +71,24 @@ int main(int argc, char *argv[]) {
* but shall accept multiple occurrences of '-' as a file
* operand.
*/
printf("argv[%d]: %s\n", i, argv[i]);
if (argv[i] == "-" || u && (argc - 1) == 1 || !u && argc == 1) {
file = fdopen(0, "r");
if (argv[i] == "-" || argc == 0) {
file = stdin;
} else if ((file = fopen(argv[i], "r")) == NULL) {
// TODO: Add error handling
fputs(usage, stderr);
return EX_NOINPUT;
}
int byte = 0;
if (u) {
while (byte != EOF) {
byte = fgetc(file);
for (char *buf = calloc(4096, 1); byte != EOF; fputs(buf, stdout)) {
byte = fgetc(file);
if (u) {
putchar(byte);
}
} else {
char *buf = calloc(1, 4096);
while (byte != EOF) {
byte = fgetc(file);
fputc(byte, fdopen(1, "r"));
} else {
snprintf(buf, 4096, "%c", byte);
}
}
if (fclose(file) == -1) {
fprintf(stderr, "%s: %s: Error closing file.\n", argv[0], argv[i]);
return EX_OSERR;
}
if (file != stdin) { fclose(file); }
}
return EX_OK;