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

55 lines
896 B
C

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "config.h"
int cat(const char *path) {
int fd = STDIN_FILENO;
if (strcmp(path, "-"))
fd = open(path, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "cat: %s: %s\n", path, strerror(errno));
return 1;
}
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;
}
if (strcmp(path, "-"))
close(fd);
return 0;
}
int main(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "")) != -1) {
printf("cat [file1 file2...]\n");
return 0;
}
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;
return ret;
}
}