实现自己的tee命令

本文详细介绍了如何使用C语言中的getopt()函数来解析命令行参数,通过示例展示了如何根据不同的参数选项实现文件操作模式,并提供了getArgs()函数的实现。通过getopt(),读者将了解如何处理命令行输入并应用于实际的终端应用程序中。
摘要由CSDN通过智能技术生成

 使用C语言终端控制函数getopt(),分析命令行参数。

C/C++ 命令解析:getopt 方法详解和使用示例_阿飞的博客-CSDN博客_c++ getopt

​

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

struct teeConfigStruct
{
    int a;
    char *outputPath;
    int outputFd;
} teeConfig;

void getArgs(int argc, char *const argv[])
{
    int opt;
    if ((opt = getopt(argc, argv, "a")) != -1)
    {
        teeConfig.a = 0;
        switch (opt)
        {
        case 'a':
            printf("追加模式\n");
            teeConfig.a = 1;
            break;
        default:
            printf("参数错误\n");
            _exit(0);
            break;
        }
    }
    if (argc - optind < 1)
    {
        printf("参数太少\n");
        _exit(0);
    }
    teeConfig.outputPath = argv[optind];
    printf("输出路径 %s \n", teeConfig.outputPath);
}

int main(int argc, char *const argv[])
{
    getArgs(argc, argv);
    int outputFileFlag;
    if (teeConfig.a == 1)
    {
        outputFileFlag = O_RDWR | O_CREAT | O_APPEND;
    }
    else
    {
        outputFileFlag = O_RDWR | O_CREAT | O_TRUNC;
    }
    teeConfig.outputFd = open(teeConfig.outputPath, outputFileFlag, 0777);
    if (teeConfig.outputFd == -1)
    {
        printf("无法打开输出文件!\n");
        _exit(0);
    }
    char buff;
    while (read(STDIN_FILENO, &buff, 1) > 0)
    {
        printf("%c", buff);
        if (write(teeConfig.outputFd, &buff, 1) == -1)
        {
            printf("无法写入!\n");
            _exit(0);
        }
    }
    if (close(teeConfig.outputFd) == -1)
    {
        printf("无法关闭文件\n");
    }
}

​

使用GCC,进行测试

​
gcc 1.c -o test

​$ ./test file

此时和tee命令选项  

​
 tee -a file

​

测试结果相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值