micro-utils/src/coreutils/cat/cat.c

55 lines
896 B
C
Raw Normal View History

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
2023-11-24 08:38:47 +00:00
#include "config.h"
2023-11-23 12:02:49 +00:00
int cat(const char *path) {
2023-11-24 08:38:47 +00:00
int fd = STDIN_FILENO;
2023-11-24 08:38:47 +00:00
if (strcmp(path, "-"))
fd = open(path, O_RDONLY);
2023-11-24 08:38:47 +00:00
if (fd < 0) {
2023-11-23 12:02:49 +00:00
fprintf(stderr, "cat: %s: %s\n", path, strerror(errno));
return 1;
}
2023-11-07 16:41:47 +00:00
2023-11-24 08:38:47 +00:00
char buf[BUF_SIZE + 1];
off_t len = 0;
while ((len = read(fd, buf, sizeof(buf))) > 0)
if (write(STDOUT_FILENO, buf, len) != len) {
fprintf(stderr, "cat: %s\n", strerror(errno));
return 1;
}
2023-11-07 16:41:47 +00:00
2023-11-29 11:05:59 +00:00
if (strcmp(path, "-"))
close(fd);
2023-11-23 12:02:49 +00:00
return 0;
}
int main(int argc, char **argv) {
int opt;
2023-11-24 08:38:47 +00:00
while ((opt = getopt(argc, argv, "")) != -1) {
2024-03-03 13:34:11 +00:00
printf("cat [file1 file2...]\n");
return 0;
2023-11-23 12:02:49 +00:00
}
argv += optind;
argc -= optind;
if (argc == 0)
return cat("-");
else {
int ret = 0;
for (int i = 0; i < argc; i++)
if (cat(argv[i]))
ret = 1;
2023-11-18 14:29:40 +00:00
return ret;
}
}