#include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define BUF_SIZE 1024 void tee(char *filename) { char szBuf[BUF_SIZE]; int fd = open(filename, O_RDWR | O_CREAT | O_APPEND, 0664); while(1) { memset(szBuf, 0, BUF_SIZE); read(STDIN_FILENO, szBuf, BUF_SIZE); fprintf(stderr, "%s", szBuf); write(fd, szBuf, strlen(szBuf)); } } int main(int argc, char **argv) { if (argc != 2 || !strcmp(argv[1], "--help")) { printf("Usage:%s [filename] ", argv[0]); printf(" filename:output file "); return 0; } tee(argv[1]); return 0; }
尚需学习:输入一个文件名,判断当前目录是否包含此文件。
更改后的程序,包含功能:如文件已存在,则实现-a命令行选项(tee -a file)在文件结尾处追加数据。
#include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define BUF_SIZE 1024 void tee(int argc, char *filename) { char szBuf[BUF_SIZE]; int fd; if (argc == 2) { fd = open(filename, O_RDWR | O_CREAT, 0664); } if (argc == 3){ fd = open(filename, O_RDWR | O_APPEND); } while(1) { memset(szBuf, 0, BUF_SIZE); read(STDIN_FILENO, szBuf, BUF_SIZE); fprintf(stderr, "%s", szBuf); write(fd, szBuf, strlen(szBuf)); } } int main(int argc, char **argv) { if ((argc != 2 && argc != 3) || !strcmp(argv[1], "--help")) { printf("Usage:%s [filename] ", argv[0]); printf(" filename:output file "); return 0; } if (argc == 2) { int iRet = access(argv[1], F_OK); // 判断文件是否存在 if (iRet == 0) { printf("File Existed "); printf("please use [-a] option "); printf("Usage:%s [-a] [filename] ", argv[0]); return 0; } tee(argc, argv[1]); } else { tee(argc, argv[2]); } return 0; }