micro-utils/coreutils/cat.c
2023-10-21 15:05:49 +03:00

56 lines
939 B
C

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
unsigned int flag;
unsigned int lines;
void cat(const int fd) {
char buf[4024];
ssize_t len;
while ((len = read(fd, buf, sizeof(buf))) > 0) {
for (ssize_t i = 0; i < len; i++) {
if (((i > 0) ? buf[i - 1] == '\n' : 1) && flag)
printf(" %d ", ++lines);
printf("%c", buf[i]);
}
}
}
int main(const int argc, const char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-n"))
flag = 1;
else if (!strcmp(argv[i], "--help")) {
printf("cat [-n (numerate)] [file1 file2 ...]\n");
return 0;
}
}
if (i == argc)
cat(STDIN_FILENO);
else {
for (; i < argc; i++) {
int fd = open(argv[i], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "cat: %s %s\n", argv[i], strerror(errno));
return 1;
}
cat(fd);
close(fd);
}
}
return 0;
}