#include <ctype.h> #include "tlpi_hdr.h" #include <stdbool.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc, char *argv[]) { char ch; bool append = FALSE; char buf[1024] = {0}; char end = EOF; int outfilefd, ret; ssize_t len; while ((ch = getopt(argc, argv, "a")) != -1) { switch (ch) { case 'a': append = TRUE; break; default: usageErr(" [-a] filename\n"); break; } } if (append && argc == 3) { outfilefd = open(argv[2], O_RDWR | O_CREAT | O_APPEND , S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (outfilefd == -1) errExit("open faild\n"); while (1) { len = read(STDIN_FILENO, buf, 1024); if (len != -1) { if (len == 0) { close(outfilefd); exit(EXIT_SUCCESS); } write(STDOUT_FILENO, buf,len); write(outfilefd, buf, len); memset(buf, 0, 1024); } } } if (append && argc == 2) { while (1) { len = read(STDIN_FILENO, buf, 1024); if (len != -1) { if (len == 0) { exit(EXIT_SUCCESS); } write(STDOUT_FILENO, buf, len); memset(buf, 0, 1024); } } } if (!append && argc == 2) { outfilefd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (outfilefd == -1) errExit("open file\n"); while (1) { len = read(STDIN_FILENO, buf, 1024); if (len != -1) { if (len == 0) { close(outfilefd); exit(EXIT_SUCCESS); } write(STDOUT_FILENO, buf, len); write(outfilefd, buf, len); memset(buf, 0, 1024); } } } if (!append && argc == 1) { while (1) { len = read(STDIN_FILENO, buf, 1024); if (len != -1) { if (len == 0) { exit(EXIT_SUCCESS); } write(STDOUT_FILENO, buf, len); memset(buf, 0, 1024); } } } exit(EXIT_SUCCESS); }
|