写一个简单的cat命令

1、本篇实现cat命令的两个基本功能

     cat  FilePath1 FilePath2 ... : 将该文件的内容输出到终端上

     cat  : 将键盘输入的内容输出到终端上

 

2、思路分析:

     以上两个功能实际上是完成了两个文件的重定向,

    cat  FilePath1 FilePath2 ... :将FilePath1 FilePath2 ... 文件中的内容重定向到了标准输出中,也就是文件拷贝的功能,即将FilePath1 FilePath2 ...的内容拷贝到了标准输出中。

   cat :  将标准输入(键盘)的内容拷贝到了标准输出中。

 

3、代码 和 测试

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define BUFFER_LEN (512)


//文件复制,将src_fd文件中的内容copy到dest_fd文件中
void copy(int src_fd,int dest_fd)
{
    if((src_fd < 0 )||(dest_fd < 0))
    {
        printf("fd error,src_fd:%d,dest_fd:%d\n",src_fd,dest_fd);

        return ;
    }

    char buf[BUFFER_LEN] = {0};
    ssize_t size = 0;

    while((size = read(src_fd,buf,BUFFER_LEN)) > 0)
    {
        if(write(dest_fd,buf,size) <= 0)
        {
            printf("write error\n");
        }
        
    }
    
}


int main(int argc ,char **argv)
{
    if((argc < 1)||(memcmp("cat",argv[0],strlen("cat")) < 0))
    {
        printf("usage: cat xxx xxx\n");

        return -1;
    }

    int std_in = STDIN_FILENO;   //标准输入 0
    int std_out = STDOUT_FILENO; //标准输出 1
    
    int i = 0;

    for(i = 1;i < argc;i ++)
    {
        std_in = open(argv[i],O_RDONLY);
        
        if(std_in < 0)
        {
            printf("%s open error\n",argv[i]);

            continue;
        }

        //将打开文件的内容copy到标准输出中去
        copy(std_in,std_out);
        close(std_in);
    }
    
    //如果只输入了 cat 命令,将标准输入的内容copy到标准输出中去
    if(argc == 1)
        copy(std_in,std_out);
    



    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KiranWang

一起努力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值