cat.c (697B)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char **argv) { int fd = 0; size_t len = 0; char buf[LINE_MAX]; while (*(++argv) != NULL) { /* if filename is "-", read file from stdin */ if ((*argv)[0] == '-' && (*argv)[1] == 0) { fd = 0; /* else, open the filename given as argument */ } else { fd = open(*argv, O_RDONLY); } if (fd < 0) { perror(*argv); } else { /* read file in chunks, and write them to stdout */ while ((len = read(fd, buf, LINE_MAX)) > 0) { write(1, buf, len); } /* gracefully close file descriptor */ close(fd); } } return 0; } |