写一个简单的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;
}

猜你喜欢

转载自blog.csdn.net/weixin_40204595/article/details/114117192
今日推荐