4-1:实现tee命令

#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]\n", argv[0]);
                printf("\tfilename:output file\n");
                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]\n", argv[0]);
                printf("\tfilename:output file\n");
                return 0;
        }
        if (argc == 2) {
                int iRet = access(argv[1], F_OK);               // 判断文件是否存在
                if (iRet == 0) {
                        printf("File Existed\n");
                        printf("please use [-a] option\n");
                        printf("Usage:%s [-a] [filename]\n", argv[0]);
                        return 0;
                }
                tee(argc, argv[1]);
        }
        else {
                tee(argc, argv[2]);
        }
        return 0;
}

 

  

 

posted @ 2018-03-15 23:36  GGBeng  阅读(279)  评论(0编辑  收藏  举报