zoukankan      html  css  js  c++  java
  • 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]
    ", 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;
    }
    

      

  • 相关阅读:
    Tomcat 调优的技巧
    双亲委派模型
    字典树实现
    Python获取房价信息和导出EXCEL
    日志检索关键字并截取上下行关联内容
    GC日志分析
    Linux 查看 删除进程
    Rotate partitions in DB2 on z
    C++ STL string
    DB2 for z: system catalog tables
  • 原文地址:https://www.cnblogs.com/xzxl/p/8577205.html
Copyright © 2011-2022 走看看