习题4-1 tee命令的实现

在文章“简单tee.c的实现”中这里写链接内容,会出现空等待的问题,我在学习的过程中修改了该代码,以备今后的学习。


对代码的分析要点:

  • 使用getopt()来解析命令行参数,多种编程语言都有实现,需要学习

  • open()打开标准输入时使用了文件描述符STDIN_FILENO-标准输入,其他文件描述符如STDOUT_FILENO-标准输出,STDERR_FILENO-标准错误


代码

/**
The tee command reads its standard input until end-of-file, writing a copy of the input
to standard output and to the file named in its command-line argument. Use getopt() to anaylsis
the command.
*/
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>

#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif

static void print_usage(void) {
    puts("usage:\n-a append to the file\n-h or -? help\ndefault:write a new file or overwrite the file\n");
    exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
    int flag_append = 0;

    const char *file_name;
    int opt;
    if ((opt = getopt(argc, argv, "ah?")) != -1) {
        switch(opt) {
            case 'a':
                flag_append = 1;
                break;
            case 'h':
            case '?':
                print_usage();
        }
    }

    if (optind >= argc) {
        exit(EXIT_FAILURE);
    }
    file_name = argv[optind];
    ssize_t num_read;
    char buf[BUF_SIZE];
    int flag = O_WRONLY | O_CREAT;
    if (flag_append) {
        flag |= O_APPEND;
    } else {
        flag |= O_TRUNC;
    }
    int fd = open(file_name,
        flag,
        S_IRUSR | S_IWUSR | S_IRGRP
        | S_IWGRP | S_IROTH | S_IWOTH );
    if (fd == -1) {
        exit(EXIT_FAILURE);
    }
    while ((num_read = read(STDIN_FILENO, buf, BUF_SIZE)) > 0) {
        write(fd, buf, num_read);
    }
    if (num_read == -1) {
        exit(EXIT_FAILURE);
    }
    if (close(fd) == -1) {
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值