overgrown/src/cat.c
2023-07-24 09:01:41 -06:00

106 lines
2.7 KiB
C

/*
* Copyright (c) 2023 YAC
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This file is part of YAC coreutils.
*
* YAC coreutils is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* YAC coreutils is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
#include <errno.h>
#include <fcntl.h>
#include <sysexits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int i = 1;
bool u = false;
char *usage_text = "(-u) [file...]";
int buf_size = strlen(argv[0]) + strlen("Usage: ") + strlen(usage_text) + 3;
char *usage = calloc(buf_size, buf_size);
if ((
snprintf(usage, buf_size, "Usage: %s (-u) [file...]\n", argv[0])
) < 0 ) {}
int opt;
while ((opt = getopt(argc, argv, "u")) != -1) {
switch(opt) {
/*
* From cat(1p):
*
* -u Write bytes from the input file to the standard output
* without delay as each is read.
*/
case 'u':
i = 2;
u = true;
break;
default:
break;
}
}
FILE *file;
for (; i <= (argc - 1); i++) {
/*
* From cat(1p):
*
* file A pathname of an input file. If no file operands are
* specified, the standard input shall be used. If a file is
* '-', the cat utility shall read from the standard input at
* that point in the sequence. The cat utility shall not close
* and reopen standard input when it is referenced in this way,
* 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");
} 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);
putchar(byte);
}
} else {
char *buf = calloc(1, 4096);
while (byte != EOF) {
byte = fgetc(file);
fputc(byte, fdopen(1, "r"));
}
}
if (fclose(file) == -1) {
fprintf(stderr, "%s: %s: Error closing file.\n", argv[0], argv[i]);
return EX_OSERR;
}
}
return EX_OK;
}